#first commit
This commit is contained in:
17
lib/core/app/app_cubit.dart
Normal file
17
lib/core/app/app_cubit.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../domain/entities/user_entity.dart';
|
||||
import 'app_state.dart';
|
||||
|
||||
class AppCubit extends Cubit<AppState> {
|
||||
AppCubit() : super(const AppState());
|
||||
|
||||
// 传入实体对象,而不是零散的 id
|
||||
void setAuth(UserEntity user) {
|
||||
emit(state.copyWith(user));
|
||||
}
|
||||
|
||||
void clearAuth() {
|
||||
emit(const AppState());
|
||||
}
|
||||
}
|
||||
20
lib/core/app/app_state.dart
Normal file
20
lib/core/app/app_state.dart
Normal file
@@ -0,0 +1,20 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
import '../domain/entities/user_entity.dart';
|
||||
|
||||
class AppState extends Equatable {
|
||||
final UserEntity? user; // 直接存实体,包含 userId, username,token 等所有信息
|
||||
|
||||
const AppState({this.user});
|
||||
|
||||
// 辅助属性:判断是否登录
|
||||
bool get isLoggedIn => user != null;
|
||||
|
||||
AppState copyWith(UserEntity? user) {
|
||||
return AppState(user: user ?? this.user);
|
||||
}
|
||||
|
||||
// 必须重写 props,UI 才会只在数据真正变化时刷新
|
||||
@override
|
||||
List<Object?> get props => [user];
|
||||
}
|
||||
4
lib/core/consts/tcp_consts.dart
Normal file
4
lib/core/consts/tcp_consts.dart
Normal file
@@ -0,0 +1,4 @@
|
||||
class TCPConsts {
|
||||
static const String TCP_IP = "1.95.137.212";
|
||||
static const int TCP_PORT = 9001;
|
||||
}
|
||||
83
lib/core/di/injection.dart
Normal file
83
lib/core/di/injection.dart
Normal file
@@ -0,0 +1,83 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../features/auth/data/datasources/auth_http_datasource.dart';
|
||||
import '../../features/auth/data/datasources/impl/auth_http_datasource_impl.dart';
|
||||
import '../../features/auth/data/repositories/auth_repository_impl.dart';
|
||||
import '../../features/auth/domain/repositories/auth_repository.dart';
|
||||
import '../../features/auth/domain/usecases/login_usecase.dart';
|
||||
import '../../features/auth/presentation/bloc/auth_cubit.dart';
|
||||
import '../../features/auth/presentation/bloc/login_bloc.dart';
|
||||
import '../../features/auth/presentation/bloc/login_cubit.dart';
|
||||
import '../app/app_cubit.dart';
|
||||
import '../network/dio_client.dart';
|
||||
import '../network/net_message_dispatcher.dart';
|
||||
import '../network/tcp/tcp_client.dart';
|
||||
import '../router/app_router.dart';
|
||||
import '../storage/impl/user_storage_impl.dart';
|
||||
import '../storage/user_storage.dart';
|
||||
|
||||
final sl = GetIt.instance;
|
||||
|
||||
Future<void> init() async {
|
||||
/// 1. 底层工具与存储 (最底层)
|
||||
/// 1.1 --- Network ---
|
||||
/// 1.1.1 Dio:Http客户端
|
||||
sl.registerLazySingleton<Dio>(() => DioClient.create());
|
||||
|
||||
/// 1.1.2 TcpClient:TCP客户端
|
||||
sl.registerLazySingleton(() => TcpClient());
|
||||
|
||||
/// 1.1.3 NetMessageDispatcher:消息调度器,并将 TcpClient 注入给它
|
||||
sl.registerLazySingleton(() => NetMessageDispatcher(sl()));
|
||||
|
||||
/// 1.2 --- 本地存储 (LocalStorage) ---
|
||||
/// 1.2.1 SharedPreferences:本地存储库
|
||||
final sharedPrefs = await SharedPreferences.getInstance();
|
||||
sl.registerLazySingleton<SharedPreferences>(() => sharedPrefs);
|
||||
|
||||
/// 1.2.2 UserStorage:用户存储库
|
||||
sl.registerLazySingleton<UserStorage>(
|
||||
// 必须先注册上面本地存储库的实例
|
||||
() => UserStorageImpl(sl<SharedPreferences>()),
|
||||
);
|
||||
|
||||
/// 2. 数据源 (DataSource)
|
||||
sl.registerLazySingleton<AuthHttpDataSource>(
|
||||
() => AuthHttpDataSourceImpl(sl()),
|
||||
);
|
||||
|
||||
/// 3. 仓库 (Repository)
|
||||
sl.registerLazySingleton<AuthRepository>(
|
||||
() => AuthRepositoryImpl(
|
||||
remote: sl(), // 自动寻找已注册的 LoginRemoteDataSource
|
||||
localTokenStorage: sl(), // 自动寻找已注册的 TokenStorage
|
||||
),
|
||||
);
|
||||
|
||||
/// 4. 用例 (UseCase)
|
||||
sl.registerLazySingleton(() => LoginUseCase(sl()));
|
||||
|
||||
/// 5. 状态管理 (Cubit/Bloc)
|
||||
sl.registerLazySingleton(() => AppCubit()); // AuthCubit 依赖它,必须先注册
|
||||
|
||||
/// 6. 认证 (Auth)
|
||||
// --- 关键修改点 1: AuthCubit 必须在 GoRouter 之前注册,并传入参数 ---
|
||||
sl.registerLazySingleton(
|
||||
() => AuthCubit(
|
||||
sl<UserStorage>(),
|
||||
sl<TcpClient>(),
|
||||
sl<AppCubit>(),
|
||||
sl<NetMessageDispatcher>(),
|
||||
),
|
||||
);
|
||||
|
||||
/// 7. 路由 (Router)
|
||||
sl.registerSingleton<GoRouter>(createRouter(sl<AuthCubit>()));
|
||||
|
||||
/// 8. 页面级 Bloc/Cubit (Factory)
|
||||
sl.registerFactory(() => LoginBloc(sl()));
|
||||
sl.registerFactory(() => LoginCubit(sl(), sl()));
|
||||
}
|
||||
32
lib/core/domain/entities/user_entity.dart
Normal file
32
lib/core/domain/entities/user_entity.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class UserEntity extends Equatable {
|
||||
final String userId;
|
||||
final String username;
|
||||
final String nickname;
|
||||
final String token;
|
||||
final String? avatar;
|
||||
final String? email;
|
||||
final String? phone;
|
||||
|
||||
UserEntity({
|
||||
required this.userId,
|
||||
required this.username,
|
||||
required this.nickname,
|
||||
required this.token,
|
||||
this.avatar,
|
||||
this.email,
|
||||
this.phone,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
userId,
|
||||
username,
|
||||
nickname,
|
||||
avatar,
|
||||
token,
|
||||
email,
|
||||
phone,
|
||||
];
|
||||
}
|
||||
5
lib/core/domain/usecases/base_usecase.dart
Normal file
5
lib/core/domain/usecases/base_usecase.dart
Normal file
@@ -0,0 +1,5 @@
|
||||
abstract class BaseUseCase<Type, Params> {
|
||||
Future<Type> call(Params params);
|
||||
}
|
||||
|
||||
class NoParams {}
|
||||
4
lib/core/error/failure.dart
Normal file
4
lib/core/error/failure.dart
Normal file
@@ -0,0 +1,4 @@
|
||||
class Failure {
|
||||
final String message;
|
||||
Failure(this.message);
|
||||
}
|
||||
16
lib/core/network/dio_client.dart
Normal file
16
lib/core/network/dio_client.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
class DioClient {
|
||||
static Dio create() {
|
||||
final dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: 'http://1.95.137.212:8081',
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 5),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
),
|
||||
);
|
||||
dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
|
||||
return dio;
|
||||
}
|
||||
}
|
||||
26
lib/core/network/net_message_dispatcher.dart
Normal file
26
lib/core/network/net_message_dispatcher.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'protocol_decoder.dart';
|
||||
import 'tcp/tcp_client.dart';
|
||||
// 注意:这里需要导入你具体的 UserModel
|
||||
// import '../../features/auth/data/models/user_model.dart';
|
||||
|
||||
class NetMessageDispatcher {
|
||||
final TcpClient tcpClient;
|
||||
NetMessageDispatcher(this.tcpClient);
|
||||
|
||||
/// 过滤特定指令的流
|
||||
Stream<RawPacket> onCommand(int commandCode) {
|
||||
return tcpClient.packetStream.where((p) => p.command == commandCode);
|
||||
}
|
||||
|
||||
/// 示例解析方法:将 0x02 指令解析为 String
|
||||
Stream<String> onStringMessage() {
|
||||
return onCommand(0x02).map((p) => utf8.decode(p.payload));
|
||||
}
|
||||
|
||||
/// 示例解析方法:将 0x12 指令解析为 JSON 并转为模型
|
||||
Stream<Map<String, dynamic>> onJsonMessage(int cmd) {
|
||||
return onCommand(cmd).map((p) => jsonDecode(utf8.decode(p.payload)));
|
||||
}
|
||||
}
|
||||
59
lib/core/network/protocol_decoder.dart
Normal file
59
lib/core/network/protocol_decoder.dart
Normal file
@@ -0,0 +1,59 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
class RawPacket {
|
||||
final int command; // 第三位指令位
|
||||
final Uint8List payload; // 数据位
|
||||
RawPacket({required this.command, required this.payload});
|
||||
}
|
||||
|
||||
class ProtocolDecoder {
|
||||
static const head = [0xAB, 0xAA];
|
||||
static const tail = [0xAA, 0xAB];
|
||||
final List<int> _buffer = [];
|
||||
|
||||
List<RawPacket> decode(List<int> newData) {
|
||||
_buffer.addAll(newData);
|
||||
List<RawPacket> packets = [];
|
||||
|
||||
while (_buffer.length >= 5) {
|
||||
// 最小包长度:头2+指令1+尾2 = 5,加1位数据=6,但是心跳包是AB AA FF AA AB
|
||||
// 1. 找头
|
||||
int headIdx = -1;
|
||||
for (int i = 0; i < _buffer.length - 1; i++) {
|
||||
if (_buffer[i] == head[0] && _buffer[i + 1] == head[1]) {
|
||||
headIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (headIdx == -1) {
|
||||
_buffer.clear(); // 没头,全是垃圾数据
|
||||
break;
|
||||
}
|
||||
|
||||
// 2. 找尾
|
||||
int tailIdx = -1;
|
||||
for (int i = headIdx + 2; i < _buffer.length - 1; i++) {
|
||||
if (_buffer[i] == tail[0] && _buffer[i + 1] == tail[1]) {
|
||||
tailIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tailIdx != -1) {
|
||||
// 3. 提取
|
||||
int cmd = _buffer[headIdx + 2];
|
||||
Uint8List payload = Uint8List.fromList(
|
||||
_buffer.sublist(headIdx + 3, tailIdx),
|
||||
);
|
||||
packets.add(RawPacket(command: cmd, payload: payload));
|
||||
|
||||
// 4. 移除已处理部分
|
||||
_buffer.removeRange(0, tailIdx + 2);
|
||||
} else {
|
||||
break; // 还没传完
|
||||
}
|
||||
}
|
||||
return packets;
|
||||
}
|
||||
}
|
||||
54
lib/core/network/tcp/tcp_client.dart
Normal file
54
lib/core/network/tcp/tcp_client.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart';
|
||||
|
||||
class TcpClient {
|
||||
Socket? _socket;
|
||||
final _decoder = ProtocolDecoder();
|
||||
// 使用 StreamController 将原始数据流暴露给外部,以便多个 DataSource 监听
|
||||
final _controller = StreamController<RawPacket>.broadcast();
|
||||
Stream<RawPacket> get packetStream => _controller.stream;
|
||||
|
||||
// 通过参数配置,不硬编码
|
||||
Future<void> connect({required String host, required int port}) async {
|
||||
try {
|
||||
_socket = await Socket.connect(
|
||||
host,
|
||||
port,
|
||||
timeout: const Duration(seconds: 5),
|
||||
);
|
||||
|
||||
_socket!.listen(
|
||||
(data) {
|
||||
var packets = _decoder.decode(data);
|
||||
for (var packet in packets) {
|
||||
_controller.add(packet);
|
||||
}
|
||||
},
|
||||
onDone: disconnect,
|
||||
onError: (e) => disconnect(),
|
||||
);
|
||||
} catch (e) {
|
||||
rethrow; // 向上抛出连接异常
|
||||
}
|
||||
}
|
||||
|
||||
void send(Map<String, dynamic> data) {
|
||||
if (_socket == null) throw Exception("Socket not connected");
|
||||
_socket!.write(jsonEncode(data));
|
||||
}
|
||||
|
||||
void sendRaw(int cmd, List<int> payload) {
|
||||
if (_socket == null) return;
|
||||
// 组装:头 AB AA + 指令 + 数据 + 尾 AA AB
|
||||
final data = [0xAB, 0xAA, cmd, ...payload, 0xAA, 0xAB];
|
||||
_socket!.add(data);
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_socket?.destroy();
|
||||
_socket = null;
|
||||
}
|
||||
}
|
||||
33
lib/core/router/app_router.dart
Normal file
33
lib/core/router/app_router.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/core/router/route_paths.dart';
|
||||
|
||||
import '../../features/auth/presentation/bloc/auth_cubit.dart';
|
||||
import '../../features/auth/presentation/bloc/auth_state.dart';
|
||||
import '../../features/auth/presentation/pages/login_page.dart';
|
||||
import '../../features/home/presentation/pages/home_page.dart';
|
||||
import '../../features/register/presentation/pages/register_page.dart';
|
||||
import 'go_router_refresh_stream.dart';
|
||||
|
||||
GoRouter createRouter(AuthCubit authCubit) {
|
||||
return GoRouter(
|
||||
initialLocation: RoutePaths.login,
|
||||
refreshListenable: GoRouterRefreshStream(authCubit.stream),
|
||||
redirect: (context, state) {
|
||||
final loggedIn = authCubit.state is AuthAuthenticated;
|
||||
final loggingIn = state.matchedLocation == RoutePaths.login;
|
||||
|
||||
if (!loggedIn && !loggingIn) {
|
||||
return RoutePaths.login;
|
||||
}
|
||||
if (loggedIn && loggingIn) {
|
||||
return RoutePaths.home;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
routes: [
|
||||
GoRoute(path: RoutePaths.login, builder: (_, __) => LoginPage()),
|
||||
GoRoute(path: RoutePaths.register, builder: (_, __) => RegisterPage()),
|
||||
GoRoute(path: RoutePaths.home, builder: (context, state) => HomePage()),
|
||||
],
|
||||
);
|
||||
}
|
||||
19
lib/core/router/go_router_refresh_stream.dart
Normal file
19
lib/core/router/go_router_refresh_stream.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class GoRouterRefreshStream extends ChangeNotifier {
|
||||
late final StreamSubscription _subscription;
|
||||
|
||||
GoRouterRefreshStream(Stream<dynamic> stream) {
|
||||
_subscription = stream.listen((_) {
|
||||
notifyListeners();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_subscription.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
5
lib/core/router/route_paths.dart
Normal file
5
lib/core/router/route_paths.dart
Normal file
@@ -0,0 +1,5 @@
|
||||
class RoutePaths {
|
||||
static const login = '/auth';
|
||||
static const register = '/register';
|
||||
static const home = '/home';
|
||||
}
|
||||
41
lib/core/storage/impl/user_storage_impl.dart
Normal file
41
lib/core/storage/impl/user_storage_impl.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../features/auth/data/models/user_model.dart';
|
||||
import '../user_storage.dart';
|
||||
|
||||
class UserStorageImpl implements UserStorage {
|
||||
final SharedPreferences _prefs;
|
||||
static const _userKey = 'auth_user';
|
||||
|
||||
UserStorageImpl(this._prefs);
|
||||
|
||||
@override
|
||||
Future<void> saveUser(UserEntity user) async {
|
||||
// 1. 将对象转为 Map -> 2. 将 Map 转为 JSON 字符串
|
||||
final model = UserModel.fromEntity(user);
|
||||
await _prefs.setString(_userKey, json.encode(model.toJson()));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<UserEntity?> getUser() async {
|
||||
final jsonString = _prefs.getString(_userKey);
|
||||
if (jsonString == null) return null;
|
||||
|
||||
// 将 JSON 转回 Model,再转成 Entity 返回给业务层
|
||||
final model = UserModel.fromJson(json.decode(jsonString));
|
||||
return model.toEntity();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deleteUser() async {
|
||||
await _prefs.remove(_userKey);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> hasUser() async {
|
||||
return _prefs.containsKey(_userKey);
|
||||
}
|
||||
}
|
||||
8
lib/core/storage/user_storage.dart
Normal file
8
lib/core/storage/user_storage.dart
Normal file
@@ -0,0 +1,8 @@
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
|
||||
abstract class UserStorage {
|
||||
Future<void> saveUser(UserEntity user);
|
||||
Future<UserEntity?> getUser();
|
||||
Future<void> deleteUser();
|
||||
Future<bool> hasUser();
|
||||
}
|
||||
Reference in New Issue
Block a user