| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235 |
- 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<int> 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<bool> 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<List<UserProfile>> 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<UserProfile> 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<String> getUsername() async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.getString("username") ?? "";
- }
- Future<String> getPassword() async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.getString("password") ?? "";
- }
- Future<bool> setUsername(String username) async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.setString("username", username);
- }
- Future<bool> setUID(int uid) async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.setInt("uid", uid);
- }
- Future<int> 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<bool> setPassword(String password) async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.setString("password", password);
- }
- Future<bool> clearPassword() async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.remove("password");
- }
- Future<bool> clearToken() async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.remove("token");
- }
- Future<bool> clearUID() async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.remove("uid");
- }
- Future<String> getToken() async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.getString("token") ?? "";
- }
- Future<bool> setToken(String token) async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.setString("token", token);
- }
- Future<bool> preLogin() async {
- if (await home() > 0) {
- return true;
- }
- return login();
- }
- logout() async {
- await method.clearToken();
- await method.clearPassword();
- await method.clearUID();
- dio = Dio();
- }
- Future<UserProfile?> 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<String, dynamic>? 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<String?> 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<bool> 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;
- }
- }
|