Commit 0d825f57 by tanghuan

优化调整

1 parent df03443e
...@@ -2,7 +2,6 @@ import 'package:appframe/config/constant.dart'; ...@@ -2,7 +2,6 @@ import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart'; import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart'; import 'package:appframe/config/routes.dart';
import 'package:appframe/data/repositories/wechat_auth_repository.dart'; import 'package:appframe/data/repositories/wechat_auth_repository.dart';
import 'package:appframe/services/im_service.dart';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluwx/fluwx.dart'; import 'package:fluwx/fluwx.dart';
...@@ -42,13 +41,11 @@ class LoginMainState extends Equatable { ...@@ -42,13 +41,11 @@ class LoginMainState extends Equatable {
class LoginMainCubit extends Cubit<LoginMainState> { class LoginMainCubit extends Cubit<LoginMainState> {
late final Fluwx _fluwx; late final Fluwx _fluwx;
late final WechatAuthRepository _wechatAuthRepository; late final WechatAuthRepository _wechatAuthRepository;
late final ImService _imService;
LoginMainCubit(super.initialState) { LoginMainCubit(super.initialState) {
_fluwx = getIt.get<Fluwx>(); _fluwx = getIt.get<Fluwx>();
_fluwx.addSubscriber(_responseListener); _fluwx.addSubscriber(_responseListener);
_wechatAuthRepository = getIt<WechatAuthRepository>(); _wechatAuthRepository = getIt<WechatAuthRepository>();
_imService = getIt.get<ImService>();
} }
void toggleAgreed(bool value) { void toggleAgreed(bool value) {
...@@ -89,6 +86,7 @@ class LoginMainCubit extends Cubit<LoginMainState> { ...@@ -89,6 +86,7 @@ class LoginMainCubit extends Cubit<LoginMainState> {
void _responseListener(WeChatResponse response) async { void _responseListener(WeChatResponse response) async {
if (response is WeChatAuthResponse) { if (response is WeChatAuthResponse) {
if (response.code == null || response.code == '') { if (response.code == null || response.code == '') {
emit(state.copyWith(loading: false));
return; return;
} }
...@@ -111,17 +109,6 @@ class LoginMainCubit extends Cubit<LoginMainState> { ...@@ -111,17 +109,6 @@ class LoginMainCubit extends Cubit<LoginMainState> {
sharedPreferences.setString('auth_stuId', stuId ?? ''); sharedPreferences.setString('auth_stuId', stuId ?? '');
sharedPreferences.setString('auth_ip', Constant.h5Server); sharedPreferences.setString('auth_ip', Constant.h5Server);
if (Constant.needIM) {
// IM登录, 正式使用时,需要从服务端获取用户签名
var loginResult = await _imService.login(userCode);
if (loginResult) {
print("微信登录处,IM 登录成功");
await _imService.registerPush();
} else {
print("微信登录处,IM 登录失败");
}
}
router.go( router.go(
'/web', '/web',
extra: { extra: {
......
...@@ -10,6 +10,7 @@ import 'package:appframe/services/dispatcher.dart'; ...@@ -10,6 +10,7 @@ import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/services/im_service.dart'; import 'package:appframe/services/im_service.dart';
import 'package:appframe/services/local_server_service.dart'; import 'package:appframe/services/local_server_service.dart';
import 'package:appframe/services/player_service.dart'; import 'package:appframe/services/player_service.dart';
import 'package:appframe/services/recorder_service.dart';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
...@@ -36,16 +37,6 @@ class WebState extends Equatable { ...@@ -36,16 +37,6 @@ class WebState extends Equatable {
final int? userType; final int? userType;
final String? stuId; final String? stuId;
/// 录音
// final bool recorderIsInit;
//final int recordState;
// final String recordPath;
/// 播放
// final bool playerIsInit;
//final int playState;
// final String playId;
/// getOrientationCmd /// getOrientationCmd
final bool orientationCmdFlag; final bool orientationCmdFlag;
final String orientationCmdMessage; final String orientationCmdMessage;
...@@ -65,7 +56,7 @@ class WebState extends Equatable { ...@@ -65,7 +56,7 @@ class WebState extends Equatable {
const WebState({ const WebState({
this.selectedIndex = 0, this.selectedIndex = 0,
this.loaded = false, this.loaded = false,
this.title = '界面加载中...', this.title = '',
this.titleColor = 0xFFFFFFFF, this.titleColor = 0xFFFFFFFF,
this.bgColor = 0xFF7691FA, this.bgColor = 0xFF7691FA,
this.opIcon = 'none', this.opIcon = 'none',
...@@ -76,12 +67,6 @@ class WebState extends Equatable { ...@@ -76,12 +67,6 @@ class WebState extends Equatable {
this.classCode, this.classCode,
this.userType, this.userType,
this.stuId, this.stuId,
// this.recorderIsInit = false,
// this.recordState = 0,
// this.recordPath = '',
// this.playerIsInit = false,
// this.playState = 0,
// this.playId = '',
this.orientationCmdFlag = false, this.orientationCmdFlag = false,
this.orientationCmdMessage = '', this.orientationCmdMessage = '',
this.windowInfoCmdFlag = false, this.windowInfoCmdFlag = false,
...@@ -107,12 +92,6 @@ class WebState extends Equatable { ...@@ -107,12 +92,6 @@ class WebState extends Equatable {
String? classCode, String? classCode,
int? userType, int? userType,
String? stuId, String? stuId,
// bool? recorderIsInit,
// int? recordState,
// String? recordPath,
// bool? playerIsInit,
// int? playState,
// String? playId,
bool? orientationCmdFlag, bool? orientationCmdFlag,
String? orientationCmdMessage, String? orientationCmdMessage,
bool? windowInfoCmdFlag, bool? windowInfoCmdFlag,
...@@ -136,12 +115,6 @@ class WebState extends Equatable { ...@@ -136,12 +115,6 @@ class WebState extends Equatable {
classCode: classCode ?? this.classCode, classCode: classCode ?? this.classCode,
userType: userType ?? this.userType, userType: userType ?? this.userType,
stuId: stuId ?? this.stuId, stuId: stuId ?? this.stuId,
// recorderIsInit: recorderIsInit ?? this.recorderIsInit,
// recordState: recordState ?? this.recordState,
// recordPath: recordPath ?? this.recordPath,
// playerIsInit: playerIsInit ?? this.playerIsInit,
// playState: playState ?? this.playState,
// playId: playId ?? this.playId,
orientationCmdFlag: orientationCmdFlag ?? this.orientationCmdFlag, orientationCmdFlag: orientationCmdFlag ?? this.orientationCmdFlag,
orientationCmdMessage: orientationCmdMessage ?? this.orientationCmdMessage, orientationCmdMessage: orientationCmdMessage ?? this.orientationCmdMessage,
windowInfoCmdFlag: windowInfoCmdFlag ?? this.windowInfoCmdFlag, windowInfoCmdFlag: windowInfoCmdFlag ?? this.windowInfoCmdFlag,
...@@ -168,12 +141,6 @@ class WebState extends Equatable { ...@@ -168,12 +141,6 @@ class WebState extends Equatable {
classCode, classCode,
userType, userType,
stuId, stuId,
// recorderIsInit,
// recordState,
// recordPath,
// playerIsInit,
// playState,
// playId,
orientationCmdFlag, orientationCmdFlag,
orientationCmdMessage, orientationCmdMessage,
windowInfoCmdFlag, windowInfoCmdFlag,
...@@ -188,84 +155,93 @@ class WebState extends Equatable { ...@@ -188,84 +155,93 @@ class WebState extends Equatable {
class WebCubit extends Cubit<WebState> { class WebCubit extends Cubit<WebState> {
late final MessageDispatcher _dispatcher; late final MessageDispatcher _dispatcher;
late final WebViewController _controller; late final WebViewController _controller;
late final HttpServer _server;
late final Fluwx _fluwx; late final Fluwx _fluwx;
late final PlayerService _playerService; HttpServer? _server;
late final PlayerService _recorderService; PlayerService? _playerService;
RecorderService? _recorderService;
// FlutterSoundRecorder? _recorder;
// StreamSubscription? _recorderSubscription;
// FlutterSoundPlayer? _player;
// StreamSubscription? _playerSubscription;
// int? _playDuration;
WebViewController get controller => _controller; WebViewController get controller => _controller;
// FlutterSoundRecorder? get recorder => _recorder;
// FlutterSoundPlayer? get player => _player;
WebCubit(super.initialState) { WebCubit(super.initialState) {
// 没有登录数据,跳转到登录页面
if (state.sessionCode == null || state.sessionCode == '') {
WidgetsBinding.instance.addPostFrameCallback((_) {
router.go('/loginMain');
});
} else {
_init();
}
}
Future<void> _init() async {
// 消息处理器 // 消息处理器
_dispatcher = MessageDispatcher(); _dispatcher = MessageDispatcher();
// WebView控制器 // 启动本地服务器
_controller = WebViewController() await _startLocalServer();
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate( // 创建WebView控制器
await _createWebViewController();
_loadHtml();
// 登录IM
_loginIM();
_fluwx = getIt.get<Fluwx>();
_playerService = getIt.get<PlayerService>();
_playerService?.sendResponse = _sendResponse;
_recorderService = getIt.get<RecorderService>();
}
Future<void> _startLocalServer() async {
// 启动本地服务器
_server = await getIt.get<LocalServerService>().startLocalServer();
}
Future<void> _createWebViewController() async {
_controller = WebViewController();
await _controller.setJavaScriptMode(JavaScriptMode.unrestricted);
await _controller.setNavigationDelegate(
NavigationDelegate( NavigationDelegate(
onUrlChange: (UrlChange url) {}, onUrlChange: (UrlChange url) {},
onPageStarted: (String url) async { onPageStarted: (String url) async {
// 进行新页面加载时,关闭录音器和播放器,(如果有打开过) // 进行新页面加载时,关闭录音器和播放器,(如果有打开过)
// closeLocalRecorder(); await _playerService?.close();
// closeLocalPlayer(); await _recorderService?.close();
await _playerService.close();
await _recorderService.close();
}, },
onPageFinished: (String url) async { onPageFinished: (String url) async {
print('onPageFinished--------------------------------->'); print('onPageFinished--------------------------------->');
print(url); print(url);
if (url == '${Constant.localServerTestFileUrl}/login.html') { /*if (url == '${Constant.localServerTestFileUrl}/login.html') {
return; return;
} }*/
// 页面加载完成时,清空录音和音频(如果有打开过)
// await clearRecording();
// await clearAudio();
_controller.runJavaScript( _controller.runJavaScript(
'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")', 'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")',
); );
finishLoading(); finishLoading();
}, },
), ),
) );
..addJavaScriptChannel("xeJsBridge", onMessageReceived: _onMessageReceived); await _controller.addJavaScriptChannel("xeJsBridge", onMessageReceived: _onMessageReceived);
}
// 启动本地服务器,并加载HTML
_startLocalServerAndLoadHtml(); void _loadHtml() {
// 构造函数中已拦截判断未登录的情况进行了处理,所以这里不再处理未登录的情况
_fluwx = getIt.get<Fluwx>(); final String serverUrl = '${Constant.localServerUrl}/index.html'
_playerService = getIt.get<PlayerService>(); '#/h5/login/pages/applogin?'
_playerService.sendResponse = _sendResponse; 'sessionCode=${state.sessionCode}&'
_recorderService = getIt.get<PlayerService>(); 'userCode=${state.userCode}&'
'classCode=${state.classCode}&'
'userType=${state.userType}&'
'stuId=${state.stuId}';
_controller.loadRequest(Uri.parse(serverUrl));
} }
void _startLocalServerAndLoadHtml() async { Future<void> _loginIM() async {
// 启动本地服务器
_server = await getIt.get<LocalServerService>().startLocalServer();
final String serverUrl;
if (state.sessionCode == null || state.sessionCode == '') {
// serverUrl = '${Constant.localServerUrl}/index.html';
serverUrl = '${Constant.localServerTestFileUrl}/login.html';
// serverUrl = '${Constant.localServerTestFileUrl}/test2.html';
} else {
// serverUrl =
// 'http://${state.ip}:${_server.port}/index.html#/h5/login/pages/applogin?sessionCode=${state.sessionCode}&userCode=${state.userCode}&classCode=${state.classCode}&userType=${state.userType}&stuId=${state.stuId}';
// IM 登录
if (Constant.needIM) { if (Constant.needIM) {
var imService = getIt.get<ImService>(); var imService = getIt.get<ImService>();
var loginResult = await imService.login(state.userCode!); var loginResult = await imService.login(state.userCode!);
...@@ -276,12 +252,6 @@ class WebCubit extends Cubit<WebState> { ...@@ -276,12 +252,6 @@ class WebCubit extends Cubit<WebState> {
print("缓存自动登录处,IM 登录失败"); print("缓存自动登录处,IM 登录失败");
} }
} }
serverUrl =
'${Constant.localServerUrl}/index.html#/h5/login/pages/applogin?sessionCode=${state.sessionCode}&userCode=${state.userCode}&classCode=${state.classCode}&userType=${state.userType}&stuId=${state.stuId}';
}
_controller.loadRequest(Uri.parse(serverUrl));
} }
void _onMessageReceived(JavaScriptMessage message) async { void _onMessageReceived(JavaScriptMessage message) async {
...@@ -303,13 +273,7 @@ class WebCubit extends Cubit<WebState> { ...@@ -303,13 +273,7 @@ class WebCubit extends Cubit<WebState> {
} }
void finishLoading() { void finishLoading() {
// emit(state.copyWith(loaded: true, title: '班小二测试', opIcon: 'none')); emit(state.copyWith(loaded: true));
emit(state.copyWith(loaded: true, title: '班小二测试'));
}
// 测试
void resetLoading() {
emit(state.copyWith(loaded: false, title: '界面加载中...'));
} }
//测试 //测试
...@@ -739,353 +703,13 @@ class WebCubit extends Cubit<WebState> { ...@@ -739,353 +703,13 @@ class WebCubit extends Cubit<WebState> {
_sendResponse(resp); _sendResponse(resp);
} }
/// 录音初始化
// Future<bool> _initRecorder(int maxDuration) async {
// // 请求麦克风权限
// var status = await Permission.microphone.request();
// if (status != PermissionStatus.granted) {
// throw RecordingPermissionException('no auth');
// }
//
// // if (state.recordState != 0) {
// // return false;
// // }
//
// final directory = await getTemporaryDirectory();
// // String recordPath = '${directory.path}/${Uuid().v5(Namespace.url.value, 'www.banxiaoer.com')}_record.aac';
// // String recordPath = '${directory.path}/${Uuid().v4()}_record.aac';
// String recordPath = '${directory.path}/${Uuid().v4()}_record.mp4';
//
// // 打开录音器
// try {
// final recorder = FlutterSoundRecorder();
// _recorder = (await recorder.openRecorder())!;
//
// if (maxDuration > 0) {
// // 设置进度回调间隔
// await _recorder!.setSubscriptionDuration(Duration(seconds: 1));
// // 监听录制进度
// _recorder!.onProgress!.listen((event) {
// // event.duration 包含当前录制时长
// // event.decibels 包含当前音量级别
// print('录制进度: ${event.duration.inSeconds}秒, 音量: ${event.decibels}');
// /*if (event.duration.inSeconds >= maxDuration) {
// stopRecording();
// }*/
// });
// }
//
// emit(state.copyWith(recorderIsInit: true, recordPath: recordPath));
// return true;
// } catch (e) {
// throw Exception('打开录音器失败!');
// }
// }
//
// /// 开始录音
// Future<bool> startRecording(int maxDuration) async {
// if (state.recorderIsInit) {
// return false;
// }
//
// // if (state.recordState != 0) {
// // return false;
// // }
//
// if (_recorder != null && !_recorder!.isStopped) {
// return false;
// }
//
// final initResult = await _initRecorder(maxDuration);
// if (!initResult) {
// return false;
// }
//
// await _recorder!.startRecorder(toFile: state.recordPath, codec: Codec.aacMP4);
// // emit(state.copyWith(recordState: 1));
// return true;
// }
//
// /// 暂停录音
// Future<bool> pauseRecording() async {
// if (!state.recorderIsInit) {
// return false;
// }
//
// // if (state.recordState != 1) {
// // return false;
// // }
//
// if (!_recorder!.isRecording) {
// return false;
// }
//
// await _recorder!.pauseRecorder();
// // emit(state.copyWith(recordState: 2));
// return true;
// }
//
// /// 恢复录音
// Future<bool> resumeRecording() async {
// if (!state.recorderIsInit) {
// return false;
// }
//
// // if (state.recordState != 2) {
// // return false;
// // }
//
// if (!_recorder!.isPaused) {
// return false;
// }
//
// await _recorder!.resumeRecorder();
// // emit(state.copyWith(recordState: 1));
// return true;
// }
//
// /// 停止录音
// Future<Map<String, dynamic>> stopRecording() async {
// if (!state.recorderIsInit) {
// throw Exception("录音器未初始化");
// }
//
// // if (state.recordState != 1 && state.recordState != 2) {
// // throw Exception("录音器状态错误");
// // }
//
// if (!_recorder!.isRecording && !_recorder!.isPaused) {
// throw Exception("录音器状态错误");
// }
//
// var url = await _recorder!.stopRecorder();
// await _recorder!.closeRecorder();
// _recorder = null;
// // emit(state.copyWith(recorderIsInit: false, recordState: 0, recordPath: ''));
// emit(state.copyWith(recorderIsInit: false, recordPath: ''));
//
// if (url == null || url.isEmpty) {
// throw Exception("录音失败");
// }
//
// var tempDir = await getTemporaryDirectory();
// String fileName = path.basenameWithoutExtension(url);
// String mp3Path = '${tempDir.path}/$fileName.mp3';
//
// // var convertResult = await compute(AudioUtil.convertAacToMp3, {'accPath': url, 'mp3Path': mp3Path});
// var convertResult = await AudioUtil.convertAacToMp3({'accPath': url, 'mp3Path': mp3Path});
// if (!convertResult) {
// throw Exception("录音转码失败");
// }
//
// // 时长
// // var duration = await AudioUtil.getAudioDuration(mp3Path);
// var duration = await AudioUtil.getAudioDuration(url);
//
// return {
// 'tempFilePath': '${Constant.localServerTempFileUrl}$mp3Path',
// 'duration': duration.inSeconds,
// };
// }
//
// /// 清空录音
// Future<bool> clearRecording() async {
// // await _recorder!.stopRecorder();
// try {
// await _recorder?.closeRecorder();
// _recorder = null;
// } catch (e) {
// print(e);
// }
// // emit(state.copyWith(recorderIsInit: false, recordState: 0, recordPath: ''));
// emit(state.copyWith(recorderIsInit: false, recordPath: ''));
// return true;
// }
/// 播放初始化
// Future<bool> _initPlayer(String playId) async {
// // 打开播放器
// try {
// final player = FlutterSoundPlayer();
// _player = (await player.openPlayer())!;
// _player!.setSpeed(2); // 播放速度,默认1
//
// // 播放进度回调
// _player!.setSubscriptionDuration(Duration(seconds: 1));
// _playerSubscription = _player!.onProgress!.listen((event) {
// print('播放回调--------- ${event.duration.inSeconds} ${event.position.inSeconds}');
//
// _playDuration = event.duration.inSeconds;
// var playPosition = event.position.inSeconds;
//
// var data = {'playId': state.playId, 'duration': _playDuration, 'currentTime': playPosition};
// var h5Cmd = {
// 'unique': '',
// 'cmd': 'audioProgress',
// 'data': data,
// 'errMsg': '',
// };
// _sendResponse(h5Cmd);
// });
//
// emit(state.copyWith(playerIsInit: true, playId: playId));
// return true;
// } catch (e) {
// throw Exception('打开播放器失败!');
// }
// }
//
// /// 播放音频
// Future<bool> playAudio(String url, int seek, String playId) async {
// if (!state.playerIsInit) {
// final initResult = await _initPlayer(playId);
// if (!initResult) {
// return false;
// }
// }
//
// await _player!.startPlayer(
// fromURI: url,
// whenFinished: () async {
// await _player!.stopPlayer();
// // emit(state.copyWith(playState: 0));
//
// // 补发一下全部进度
// var h5Cmd = {
// 'unique': '',
// 'cmd': 'audioProgress',
// 'data': {'playId': state.playId, 'duration': _playDuration, 'currentTime': _playDuration},
// 'errMsg': '',
// };
// _sendResponse(h5Cmd);
//
// // 播放结束后,发送消息给客户端
// h5Cmd = {
// 'unique': '',
// 'cmd': 'audioEnd',
// 'data': {'playId': state.playId},
// 'errMsg': '',
// };
// _sendResponse(h5Cmd);
// },
// );
// if (seek != 0) {
// await seekAudio(seek);
// }
// // emit(state.copyWith(playState: 1));
// return true;
// }
//
// /// 暂停播放
// Future<bool> pauseAudio() async {
// if (!state.playerIsInit) {
// throw Exception("播放器未初始化");
// }
//
// // if (state.playState != 1) {
// // throw Exception("播放器状态错误");
// // }
//
// if (!_player!.isPlaying) {
// throw Exception("播放器状态错误");
// }
//
// await _player!.pausePlayer();
// // emit(state.copyWith(playState: 2));
// return true;
// }
//
// /// 恢复播放
// Future<bool> resumeAudio() async {
// if (!state.playerIsInit) {
// throw Exception("播放器未初始化");
// }
//
// // if (state.playState != 2) {
// // throw Exception("播放器状态错误");
// // }
//
// if (!_player!.isPaused) {
// throw Exception("播放器状态错误");
// }
//
// await _player!.resumePlayer();
// // emit(state.copyWith(playState: 1));
// return true;
// }
//
// /// 跳转播放
// Future<bool> seekAudio(int seek) async {
// if (!state.playerIsInit) {
// throw Exception("播放器未初始化");
// }
//
// await _player!.seekToPlayer(Duration(seconds: seek));
// // emit(state.copyWith(playState: 1));
// return true;
// }
//
// /// 停止播放
// Future<bool> stopAudio() async {
// if (!state.playerIsInit) {
// throw Exception("播放器未初始化");
// }
//
// // if (state.playState != 1 && state.playState != 2) {
// // throw Exception("播放器状态错误");
// // }
//
// if (!_player!.isPlaying && !_player!.isPaused) {
// throw Exception("播放器状态错误");
// }
//
// await _player!.stopPlayer();
// // emit(state.copyWith(playState: 0));
// return true;
// }
//
// /// 清空播放
// Future<bool> clearAudio() async {
// try {
// await _player?.closePlayer();
// _player = null;
// await _playerSubscription?.cancel();
// _playerSubscription = null;
// _playDuration = null;
// } catch (e) {
// print(e);
// }
// // emit(state.copyWith(playerIsInit: false, playState: 0, playId: ''));
// emit(state.copyWith(playerIsInit: false, playId: ''));
// return true;
// }
@override @override
Future<void> close() async { Future<void> close() async {
_server.close(); _server?.close();
// _fluwx.removeSubscriber(_responseListener); // _fluwx.removeSubscriber(_responseListener);
// closeLocalRecorder();
// closeLocalPlayer();
await _playerService.close();
await _recorderService.close();
// try { await _playerService?.close();
// await _recorder?.closeRecorder(); await _recorderService?.close();
// _recorder = null;
// } catch (e) {
// print(e);
// }
// try {
// await _player?.closePlayer();
// _player = null;
// await _playerSubscription?.cancel();
// _playerSubscription = null;
// _playDuration = null;
// } catch (e) {
// print(e);
// }
return super.close(); return super.close();
} }
......
...@@ -12,29 +12,12 @@ import 'package:path_provider/path_provider.dart'; ...@@ -12,29 +12,12 @@ import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
class UploadFileHandler extends MessageHandler { class UploadFileHandler extends MessageHandler {
// late Dio _dio;
// UploadFile5Handler() : _dio = Dio() {
// // _dio.httpClientAdapter = Http2Adapter(
// // ConnectionManager(idleTimeout: Duration(seconds: 10)),
// // );
//
// int connectTimeout = 30000;
// int receiveTimeout = 30000;
//
// _dio.options = BaseOptions(
// baseUrl: '',
// connectTimeout: Duration(milliseconds: connectTimeout),
// receiveTimeout: Duration(milliseconds: receiveTimeout),
// headers: {'Content-Type': '', 'Accept': ''},
// );
// }
@override @override
Future<dynamic> handleMessage(params) async { Future<dynamic> handleMessage(params) async {
if (params is! Map<String, dynamic>) { if (params is! Map<String, dynamic>) {
throw Exception('参数错误'); throw Exception('参数错误');
} }
final String? tempFilePath = params['tempFilePath'] as String?; final String? tempFilePath = params['tempFilePath'] as String?;
if (tempFilePath == null || tempFilePath.isEmpty) { if (tempFilePath == null || tempFilePath.isEmpty) {
throw Exception('参数错误'); throw Exception('参数错误');
...@@ -50,18 +33,6 @@ class UploadFileHandler extends MessageHandler { ...@@ -50,18 +33,6 @@ class UploadFileHandler extends MessageHandler {
throw Exception('参数错误'); throw Exception('参数错误');
} }
// _dio = Dio()
// ..options = BaseOptions(
// baseUrl: '',
// connectTimeout: Duration(milliseconds: 30000),
// receiveTimeout: Duration(milliseconds: 30000),
// headers: {'Content-Type': '', 'Accept': ''},
// )
// /*..httpClientAdapter = Http2Adapter(
// ConnectionManager(idleTimeout: Duration(seconds: 10)),
// )*/
// ;
final startTime = DateTime.now(); final startTime = DateTime.now();
final result = await _handle(tempFilePath, busi, subBusi); final result = await _handle(tempFilePath, busi, subBusi);
final endTime = DateTime.now(); final endTime = DateTime.now();
...@@ -205,7 +176,6 @@ class UploadFileHandler extends MessageHandler { ...@@ -205,7 +176,6 @@ class UploadFileHandler extends MessageHandler {
futures.clear(); futures.clear();
await randomAccessFile.close(); await randomAccessFile.close();
dio.close(force: true);
/// ///
/// 7 合并 /// 7 合并
...@@ -215,12 +185,21 @@ class UploadFileHandler extends MessageHandler { ...@@ -215,12 +185,21 @@ class UploadFileHandler extends MessageHandler {
var endTime2 = DateTime.now(); var endTime2 = DateTime.now();
print('====================>合并签名耗时:${endTime2.millisecondsSinceEpoch - startTime2.millisecondsSinceEpoch} 毫秒'); print('====================>合并签名耗时:${endTime2.millisecondsSinceEpoch - startTime2.millisecondsSinceEpoch} 毫秒');
///
/// 8 针对视频生成封面
///
// if (mimeType?.startsWith('video/') ?? false) {
// await _genHwVideoCover(dio, objectKey);
// }
dio.close(force: true);
bxeApiService.close(); bxeApiService.close();
return {'url': _addPreUrl(location)}; return {'url': _addPreUrl(location)};
} }
static const _bxeBaseUrl = 'https://iotapp-dev.banxiaoer.com/iotapp'; static const _bxeBaseUrl = 'https://iotapp-dev.banxiaoer.com/iotapp';
static const _genBaseUrl = 'https://dev.banxiaoer.net';
static const _signatureNewUrl = '/api/v1/obs/multipart/signaturenew'; static const _signatureNewUrl = '/api/v1/obs/multipart/signaturenew';
static const _signatureNextUrl = '/api/v1/obs/multipart/signaturenext'; static const _signatureNextUrl = '/api/v1/obs/multipart/signaturenext';
static const _completeUrl = '/api/v1/obs/multipart/complete'; static const _completeUrl = '/api/v1/obs/multipart/complete';
...@@ -280,7 +259,7 @@ class UploadFileHandler extends MessageHandler { ...@@ -280,7 +259,7 @@ class UploadFileHandler extends MessageHandler {
} }
/// 上传段 /// 上传段
Future<Response> _uploadChunk(Dio dio,String signUrl, Uint8List chunk, int chunkIndex) async { Future<Response> _uploadChunk(Dio dio, String signUrl, Uint8List chunk, int chunkIndex) async {
var url = signUrl.replaceFirst('AWSAccessKeyId=', 'AccessKeyId=').replaceFirst(':443', ''); var url = signUrl.replaceFirst('AWSAccessKeyId=', 'AccessKeyId=').replaceFirst(':443', '');
try { try {
// Response response = await _put(url, chunk); // Response response = await _put(url, chunk);
...@@ -348,4 +327,26 @@ class UploadFileHandler extends MessageHandler { ...@@ -348,4 +327,26 @@ class UploadFileHandler extends MessageHandler {
} }
} }
/// 生成封面
Future<void> _genHwVideoCover(Dio dio, String keys) async {
try {
var headers = {
"api-key": 'FJ9qv53Bxp',
};
var params = {
"videoKeys": keys,
"outputSuffix": "_p1",
};
await dio.post(
'$_genBaseUrl/go/mpc/create_covers',
data: params,
options: Options(
headers: headers,
contentType: 'application/json',
),
);
} catch (e) {
print(e);
}
}
} }
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!