Method.dart 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'dart:typed_data';
  4. import 'package:dio/dio.dart';
  5. import 'package:flutter/cupertino.dart';
  6. import 'package:flutter_easyloading/flutter_easyloading.dart';
  7. import 'package:flutter_styled_toast/flutter_styled_toast.dart';
  8. import 'package:path_provider/path_provider.dart';
  9. import 'package:permission_handler/permission_handler.dart';
  10. import 'package:shared_preferences/shared_preferences.dart';
  11. import 'Entities.dart';
  12. const api = "http://api.ignatz.xyz";
  13. final method = Method._();
  14. class Method {
  15. Method._();
  16. var dio = Dio();
  17. var options = Options();
  18. Future<int> home() async {
  19. try {
  20. final res = await dio.get("$api/home");
  21. if (res.statusCode == HttpStatus.ok) {
  22. var data = jsonDecode(res.toString());
  23. final uid = data["uid"];
  24. if (await setUID(uid)) return uid;
  25. }
  26. } on Exception catch(e) {
  27. debugPrint("home 网络错误");
  28. // debugPrint(e.toString());
  29. return 0;
  30. }
  31. return 0;
  32. }
  33. Future<bool> login() async {
  34. final username = await getUsername();
  35. final password = await getPassword();
  36. debugPrint('login: username=$username password=$password');
  37. if (username.isEmpty || password.isEmpty) return false;
  38. try {
  39. final res = await dio.post("$api/token", data: {
  40. "username": username, "password": password});
  41. if (res.statusCode == HttpStatus.ok) {
  42. var data = jsonDecode(res.toString());
  43. final token = data['token'];
  44. dio = Dio(BaseOptions(headers: {
  45. HttpHeaders.authorizationHeader: "Bearer $token"
  46. }));
  47. debugPrint('token=$token');
  48. setToken(token);
  49. return true;
  50. }
  51. } on Exception catch(e) {
  52. debugPrint("login 网络错误");
  53. return false;
  54. }
  55. return false;
  56. }
  57. Future<List<UserProfile>> getFriends({int depth=0}) async {
  58. try {
  59. final res = await dio.get('$api/friends');
  60. switch (res.statusCode) {
  61. case HttpStatus.ok:
  62. var data = jsonDecode(res.toString());
  63. List<UserProfile> friends = [];
  64. data["friends"].forEach((v) => friends.add(UserProfile.fromJson(v)));
  65. debugPrint(friends.toString());
  66. return friends;
  67. case HttpStatus.unauthorized:
  68. if (depth < 3) {
  69. login();
  70. return getFriends(depth: depth+1);
  71. }
  72. }
  73. } on Exception catch (e) {
  74. debugPrint("网络错误");
  75. return [];
  76. }
  77. return [];
  78. }
  79. Future<String> getUsername() async {
  80. final prefs = await SharedPreferences.getInstance();
  81. return prefs.getString("username") ?? "";
  82. }
  83. Future<String> getPassword() async {
  84. final prefs = await SharedPreferences.getInstance();
  85. return prefs.getString("password") ?? "";
  86. }
  87. Future<bool> setUsername(String username) async {
  88. final prefs = await SharedPreferences.getInstance();
  89. return prefs.setString("username", username);
  90. }
  91. Future<bool> setUID(int uid) async {
  92. final prefs = await SharedPreferences.getInstance();
  93. return prefs.setInt("uid", uid);
  94. }
  95. Future<int> getUID() async {
  96. final prefs = await SharedPreferences.getInstance();
  97. int uid = prefs.getInt("uid") ?? 0;
  98. if (uid == 0) uid = await home();
  99. print('uid=$uid');
  100. return uid;
  101. }
  102. Future<bool> setPassword(String password) async {
  103. final prefs = await SharedPreferences.getInstance();
  104. return prefs.setString("password", password);
  105. }
  106. Future<bool> clearPassword() async {
  107. final prefs = await SharedPreferences.getInstance();
  108. return prefs.remove("password");
  109. }
  110. Future<bool> clearToken() async {
  111. final prefs = await SharedPreferences.getInstance();
  112. return prefs.remove("token");
  113. }
  114. Future<bool> clearUID() async {
  115. final prefs = await SharedPreferences.getInstance();
  116. return prefs.remove("uid");
  117. }
  118. Future<String> getToken() async {
  119. final prefs = await SharedPreferences.getInstance();
  120. return prefs.getString("token") ?? "";
  121. }
  122. Future<bool> setToken(String token) async {
  123. final prefs = await SharedPreferences.getInstance();
  124. return prefs.setString("token", token);
  125. }
  126. Future<bool> preLogin() async {
  127. if (await home() > 0) {
  128. return true;
  129. }
  130. return login();
  131. }
  132. logout() async {
  133. await method.clearToken();
  134. await method.clearPassword();
  135. await method.clearUID();
  136. dio = Dio();
  137. }
  138. Future<UserProfile?> getProfile([String? name]) async {
  139. name = name ?? await getUsername();
  140. debugPrint("get profile of $name");
  141. final res = await dio.get("$api/profile/$name");
  142. if (res.statusCode == HttpStatus.ok) {
  143. final data = jsonDecode(res.toString());
  144. final profile = UserProfile.fromJson(data["profile"]);
  145. debugPrint("profile get, name=${profile.name}");
  146. return profile;
  147. }
  148. return null;
  149. }
  150. Future download(
  151. String url,
  152. String savePath, {
  153. Map<String, dynamic>? queryParams,
  154. CancelToken? cancelToken,
  155. dynamic data,
  156. Options? options,
  157. void Function(int, int)? onReceiveProgress,
  158. }) async {
  159. try {
  160. return await dio.download(
  161. url,
  162. savePath,
  163. queryParameters: queryParams,
  164. cancelToken: cancelToken,
  165. onReceiveProgress: onReceiveProgress,
  166. );
  167. } on DioError catch (e) {
  168. print(e);
  169. if (CancelToken.isCancel(e)) {
  170. EasyLoading.showInfo('下载已取消!');
  171. } else {
  172. if (e.response != null) {
  173. // _handleErrorResponse(e.response);
  174. } else {
  175. EasyLoading.showError(e.message);
  176. }
  177. }
  178. } on Exception catch (e) {
  179. EasyLoading.showError(e.toString());
  180. }
  181. }
  182. Future<String?> downloadImage(String path, String fileServer) async {
  183. Directory dir = await getApplicationDocumentsDirectory();
  184. String dirPath = dir.path;
  185. final savePath = "$dirPath/$path";
  186. File file = File(savePath);
  187. debugPrint("savePath=$savePath");
  188. if (file.existsSync()) return savePath;
  189. try {
  190. final res = await dio.download('$fileServer/$path', savePath);
  191. debugPrint(res.toString());
  192. } on Exception catch (e) {
  193. debugPrint("文件下载失败");
  194. return null;
  195. }
  196. return savePath;
  197. }
  198. Future<bool> updateAvatar(Uint8List buff, String suf) async {
  199. final file = MultipartFile.fromBytes(buff, filename: 'avatar$suf');
  200. final res = await dio.post("$api/avatar", data: FormData.fromMap({"file": file}));
  201. if (res.statusCode == HttpStatus.ok) {
  202. return true;
  203. }
  204. return false;
  205. }
  206. }