web_cubit.dart
32.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart';
import 'package:appframe/data/models/message/h5_message.dart';
import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/services/im_service.dart';
import 'package:appframe/services/local_server_service.dart';
import 'package:appframe/services/player_service.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluwx/fluwx.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
class WebState extends Equatable {
final int selectedIndex;
final bool loaded;
final String title;
final int titleColor;
final int bgColor;
final String opIcon;
final bool showBottomNavBar;
final String? ip;
final String? sessionCode;
final String? userCode;
final String? classCode;
final int? userType;
final String? stuId;
/// 录音
// final bool recorderIsInit;
//final int recordState;
// final String recordPath;
/// 播放
// final bool playerIsInit;
//final int playState;
// final String playId;
/// getOrientationCmd
final bool orientationCmdFlag;
final String orientationCmdMessage;
/// getWindowInfoCmd
final bool windowInfoCmdFlag;
final String windowInfoCmdMessage;
/// chooseImageCmd
final bool chooseImageCmdFlag;
final String chooseImageCmdMessage;
/// chooseVideoCmd
final bool chooseVideoCmdFlag;
final String chooseVideoCmdMessage;
const WebState({
this.selectedIndex = 0,
this.loaded = false,
this.title = '界面加载中...',
this.titleColor = 0xFFFFFFFF,
this.bgColor = 0xFF7691FA,
this.opIcon = 'none',
this.showBottomNavBar = false,
this.ip,
this.sessionCode,
this.userCode,
this.classCode,
this.userType,
this.stuId,
// this.recorderIsInit = false,
// this.recordState = 0,
// this.recordPath = '',
// this.playerIsInit = false,
// this.playState = 0,
// this.playId = '',
this.orientationCmdFlag = false,
this.orientationCmdMessage = '',
this.windowInfoCmdFlag = false,
this.windowInfoCmdMessage = '',
this.chooseImageCmdFlag = false,
this.chooseImageCmdMessage = '',
this.chooseVideoCmdFlag = false,
this.chooseVideoCmdMessage = '',
});
WebState copyWith({
int? selectedIndex,
bool? loaded,
String? title,
int? titleColor,
int? bgColor,
String? opIcon,
bool? showNavBar,
bool? showBottomNavBar,
String? ip,
String? sessionCode,
String? userCode,
String? classCode,
int? userType,
String? stuId,
// bool? recorderIsInit,
// int? recordState,
// String? recordPath,
// bool? playerIsInit,
// int? playState,
// String? playId,
bool? orientationCmdFlag,
String? orientationCmdMessage,
bool? windowInfoCmdFlag,
String? windowInfoCmdMessage,
bool? chooseImageCmdFlag,
String? chooseImageCmdMessage,
bool? chooseVideoCmdFlag,
String? chooseVideoCmdMessage,
}) {
return WebState(
selectedIndex: selectedIndex ?? this.selectedIndex,
loaded: loaded ?? this.loaded,
title: title ?? this.title,
titleColor: titleColor ?? this.titleColor,
bgColor: bgColor ?? this.bgColor,
opIcon: opIcon ?? this.opIcon,
showBottomNavBar: showBottomNavBar ?? this.showBottomNavBar,
ip: ip ?? this.ip,
sessionCode: sessionCode ?? this.sessionCode,
userCode: userCode ?? this.userCode,
classCode: classCode ?? this.classCode,
userType: userType ?? this.userType,
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,
orientationCmdMessage: orientationCmdMessage ?? this.orientationCmdMessage,
windowInfoCmdFlag: windowInfoCmdFlag ?? this.windowInfoCmdFlag,
windowInfoCmdMessage: windowInfoCmdMessage ?? this.windowInfoCmdMessage,
chooseImageCmdFlag: chooseImageCmdFlag ?? this.chooseImageCmdFlag,
chooseImageCmdMessage: chooseImageCmdMessage ?? this.chooseImageCmdMessage,
chooseVideoCmdFlag: chooseVideoCmdFlag ?? this.chooseVideoCmdFlag,
chooseVideoCmdMessage: chooseVideoCmdMessage ?? this.chooseVideoCmdMessage,
);
}
@override
List<Object?> get props => [
selectedIndex,
loaded,
title,
titleColor,
bgColor,
opIcon,
showBottomNavBar,
ip,
sessionCode,
userCode,
classCode,
userType,
stuId,
// recorderIsInit,
// recordState,
// recordPath,
// playerIsInit,
// playState,
// playId,
orientationCmdFlag,
orientationCmdMessage,
windowInfoCmdFlag,
windowInfoCmdMessage,
chooseImageCmdFlag,
chooseImageCmdMessage,
chooseVideoCmdFlag,
chooseVideoCmdMessage,
];
}
class WebCubit extends Cubit<WebState> {
late final MessageDispatcher _dispatcher;
late final WebViewController _controller;
late final HttpServer _server;
late final Fluwx _fluwx;
late final PlayerService _playerService;
late final PlayerService _recorderService;
// FlutterSoundRecorder? _recorder;
// StreamSubscription? _recorderSubscription;
// FlutterSoundPlayer? _player;
// StreamSubscription? _playerSubscription;
// int? _playDuration;
WebViewController get controller => _controller;
// FlutterSoundRecorder? get recorder => _recorder;
// FlutterSoundPlayer? get player => _player;
WebCubit(super.initialState) {
// 消息处理器
_dispatcher = MessageDispatcher();
// WebView控制器
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onUrlChange: (UrlChange url) {},
onPageStarted: (String url) async {
// 进行新页面加载时,关闭录音器和播放器,(如果有打开过)
// closeLocalRecorder();
// closeLocalPlayer();
await _playerService.close();
await _recorderService.close();
},
onPageFinished: (String url) async {
print('onPageFinished--------------------------------->');
print(url);
if (url == '${Constant.localServerTestFileUrl}/login.html') {
return;
}
// 页面加载完成时,清空录音和音频(如果有打开过)
// await clearRecording();
// await clearAudio();
_controller.runJavaScript(
'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")',
);
finishLoading();
},
),
)
..addJavaScriptChannel("xeJsBridge", onMessageReceived: _onMessageReceived);
// 启动本地服务器,并加载HTML
_startLocalServerAndLoadHtml();
_fluwx = getIt.get<Fluwx>();
_playerService = getIt.get<PlayerService>();
_playerService.sendResponse = _sendResponse;
_recorderService = getIt.get<PlayerService>();
}
void _startLocalServerAndLoadHtml() 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) {
var imService = getIt.get<ImService>();
var loginResult = await imService.login(state.userCode!);
if (loginResult) {
print("缓存自动登录处,IM 登录成功");
await imService.registerPush();
} else {
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 {
try {
_dispatcher.dispatch(message.message, (response) {
_sendResponse(response);
}, webCubit: this);
} catch (e) {
print('消息解析错误: $e');
}
}
// 向H5发送响应
void _sendResponse(Map<String, dynamic> response) {
String jsonString = jsonEncode(response);
String escapedJson = jsonString.replaceAll('"', '\\"');
final String script = 'xeJsBridgeCallback("$escapedJson");';
_controller.runJavaScript(script);
}
void finishLoading() {
// emit(state.copyWith(loaded: true, title: '班小二测试', opIcon: 'none'));
emit(state.copyWith(loaded: true, title: '班小二测试'));
}
// 测试
void resetLoading() {
emit(state.copyWith(loaded: false, title: '界面加载中...'));
}
//测试
void goWechatAuth() {
router.go('/wechatAuth');
}
void goLogin() {
router.go('/loginMain');
}
void goIm() {
router.go('/im');
}
//测试
void goAuth() {
// String serverUrl = 'http://${state.ip}:${_server.port}/index.html';
String serverUrl = '${Constant.localServerUrl}/index.html';
// String serverUrl = 'http://localdev.banxiaoer.net';
_controller.loadRequest(Uri.parse(serverUrl));
}
void goMiniProgram() {
_fluwx
// ..addSubscriber(_responseListener)
..open(
target: MiniProgram(
username: 'gh_9a8d84445828',
path: '/pages/index/index?classCode=needswitch',
miniProgramType: WXMiniProgramType.preview,
),
);
// _fluwx.share(WeChatShareTextModel("source text", scene: WeChatScene.session));
}
// void _responseListener(response) {
// if (response is WeChatLaunchMiniProgramResponse) {
// print("小程序跳转 1 --------------------------------");
// print(response);
// }
// }
Future<String?> goScanCode() async {
var result = await router.push('/scanCode');
return result as String?;
}
Future<void> handleBack() async {
// navigateBack指令
var resp = {'unique': '', 'cmd': 'navigateBack', 'data': '', 'errMsg': ''};
_sendResponse(resp);
}
Future<void> handleHome() async {
// navigateHome指令
var resp = {'unique': '', 'cmd': 'navigateHome', 'data': '', 'errMsg': ''};
_sendResponse(resp);
}
Future<void> handleRefreshPage() async {
// refreshPage指令
var resp = {'unique': '', 'cmd': 'refreshPage', 'data': '', 'errMsg': ''};
_sendResponse(resp);
}
bool setTitleBar(String title, String color, String bgColor, String icon) {
int parsedTitleColor = _hexStringToInt(color);
int parsedBgColor = _hexStringToInt(bgColor);
emit(state.copyWith(title: title, titleColor: parsedTitleColor, bgColor: parsedBgColor, opIcon: icon));
return true;
}
int _hexStringToInt(String hexString) {
// 移除可能存在的 # 前缀
if (hexString.startsWith('#')) {
hexString = hexString.substring(1);
}
// 确保颜色值是8位(包含alpha通道)
if (hexString.length == 6) {
hexString = 'FF$hexString'; // 添加不透明的alpha值
}
// 解析十六进制字符串为整数
return int.parse(hexString, radix: 16);
}
Future<void> refresh() async {
// await clearRecording();
// await clearAudio();
_controller.reload();
}
Future<void> clearStorage() async {
await getIt.get<SharedPreferences>().clear();
}
Future<void> logout() async {
await clearStorage();
// IM 登出
await getIt.get<ImService>().logout();
goLogin();
}
void updateSelectedIndex(int index) {
emit(state.copyWith(selectedIndex: index));
}
void showBottomNavBar() {
emit(state.copyWith(showBottomNavBar: true));
}
void hideBottomNavBar() {
emit(state.copyWith(showBottomNavBar: false));
}
///
///
///
void setChooseImageCmdFlag(bool chooseImageCmdFlag, String chooseImageCmdMessage) {
emit(state.copyWith(chooseImageCmdFlag: chooseImageCmdFlag, chooseImageCmdMessage: chooseImageCmdMessage));
}
void chooseImage(BuildContext context) async {
final Map<String, dynamic> data = json.decode(state.chooseImageCmdMessage);
H5Message h5Message = H5Message.fromJson(data);
setChooseImageCmdFlag(false, '');
final params = h5Message.params;
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
var sourceType = params['sourceType'] as String;
if (sourceType != 'album' && sourceType != 'camera') {
sourceType = 'album';
}
// 暂时忽略 sizeType 参数
int count = 9;
if (params.containsKey('count')) {
count = params['count'] as int;
if (count < 1 || count > 9) {
count = 9;
}
}
// 相册
if (sourceType == 'album') {
_chooseImageFromAlbum(context, count, h5Message.unique, h5Message.cmd);
}
// 拍照
else {
_chooseImageFromCamera(context, h5Message.unique, h5Message.cmd);
}
}
void _chooseImageFromAlbum(BuildContext context, int count, String unique, String cmd) async {
final List<AssetEntity>? result = await AssetPicker.pickAssets(
context,
pickerConfig: AssetPickerConfig(
maxAssets: count,
requestType: RequestType.image,
gridThumbnailSize: const ThumbnailSize.square(80),
previewThumbnailSize: const ThumbnailSize.square(150),
dragToSelect: false,
),
);
if (result == null || result.isEmpty) {
var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
_sendResponse(resp);
return;
}
// 获取临时目录
final Directory tempDir = await getTemporaryDirectory();
final List<Map<String, dynamic>> resultList = [];
for (var asset in result) {
resultList.add(await _handleSingleImage(asset, tempDir));
}
var resp = {
'unique': unique,
'cmd': cmd,
'data': {'tempFiles': resultList},
'errMsg': '',
};
_sendResponse(resp);
}
void _chooseImageFromCamera(BuildContext context, String unique, String cmd) async {
AssetEntity? asset = await CameraPicker.pickFromCamera(context, pickerConfig: const CameraPickerConfig());
if (asset == null) {
var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
_sendResponse(resp);
return;
}
final Directory tempDir = await getTemporaryDirectory();
final Map<String, dynamic> result = await _handleSingleImage(asset, tempDir);
var resp = {
'unique': unique,
'cmd': cmd,
'data': {
'tempFiles': [result],
},
'errMsg': '',
};
_sendResponse(resp);
}
Future<Map<String, dynamic>> _handleSingleImage(AssetEntity asset, Directory tempDir) async {
final file = await asset.file;
// 生成缩略图
final data = await asset.thumbnailData;
final thumbnailFile = await File(
'${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.png',
).writeAsBytes(data!);
return {
"tempFilePath": '${Constant.localServerTempFileUrl}${file!.path}',
"size": file.lengthSync(),
"width": asset.width,
"height": asset.height,
"thumbTempFilePath": '${Constant.localServerTempFileUrl}${thumbnailFile.path}',
"fileType": file.path.split('/').last.split('.').last,
};
}
void setChooseVideoCmdFlag(bool chooseVideoCmdFlag, String chooseVideoCmdMessage) {
emit(state.copyWith(chooseVideoCmdFlag: chooseVideoCmdFlag, chooseVideoCmdMessage: chooseVideoCmdMessage));
}
void chooseVideo(BuildContext context) async {
final Map<String, dynamic> data = json.decode(state.chooseVideoCmdMessage);
H5Message h5Message = H5Message.fromJson(data);
setChooseVideoCmdFlag(false, '');
final params = h5Message.params;
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
var sourceType = params['sourceType'] as String;
if (sourceType != 'album' && sourceType != 'camera') {
sourceType = 'album';
}
// 暂时忽略 sizeType 参数
int count = 1;
if (params.containsKey('count')) {
count = params['count'] as int;
if (count < 1 || count > 9) {
count = 9;
}
}
int maxDuration = 60;
if (params.containsKey('maxDuration')) {
maxDuration = params['maxDuration'] as int;
if (maxDuration < 1 || maxDuration > 600) {
maxDuration = 60;
}
}
// 相册选择
if (sourceType == 'album') {
_chooseVideoFromAlbum(context, count, h5Message.unique, h5Message.cmd);
}
// 拍摄
else {
_chooseVideoFromCamera(context, maxDuration, h5Message.unique, h5Message.cmd);
}
}
void _chooseVideoFromAlbum(BuildContext context, int count, String unique, String cmd) async {
final List<AssetEntity>? result = await AssetPicker.pickAssets(
context,
pickerConfig: AssetPickerConfig(
maxAssets: count,
requestType: RequestType.video,
dragToSelect: false,
),
);
if (result == null || result.isEmpty) {
var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
_sendResponse(resp);
return;
}
// 获取临时目录
final Directory tempDir = await getTemporaryDirectory();
final List<Map<String, dynamic>> resultList = [];
for (var asset in result) {
resultList.add(await _handleSingleVideo(asset, tempDir));
}
var resp = {
'unique': unique,
'cmd': cmd,
'data': {'tempFiles': resultList},
'errMsg': '',
};
_sendResponse(resp);
}
void _chooseVideoFromCamera(BuildContext context, int maxDuration, String unique, String cmd) async {
AssetEntity? asset = await CameraPicker.pickFromCamera(
context,
pickerConfig: CameraPickerConfig(
enableRecording: true,
onlyEnableRecording: true,
// enableTapRecording: true,
maximumRecordingDuration: Duration(seconds: maxDuration),
),
);
if (asset == null) {
var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
_sendResponse(resp);
return;
}
final Directory tempDir = await getTemporaryDirectory();
final Map<String, dynamic> result = await _handleSingleVideo(asset, tempDir);
var resp = {
'unique': unique,
'cmd': cmd,
'data': {
'tempFiles': [result],
},
'errMsg': '',
};
_sendResponse(resp);
}
Future<Map<String, dynamic>> _handleSingleVideo(AssetEntity asset, Directory tempDir) async {
final file = await asset.file;
// 获取缩略图
final data = await asset.thumbnailData;
final thumbnailFile = await File(
'${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.png',
).writeAsBytes(data!);
return {
"tempFilePath": '${Constant.localServerTempFileUrl}${file!.path}',
"size": file.lengthSync(),
"width": asset.width,
"height": asset.height,
"thumbTempFilePath": '${Constant.localServerTempFileUrl}${thumbnailFile.path}',
"fileType": file.path.split('/').last.split('.').last,
};
}
void setOrientationCmdFlag(bool orientationCmdFlag, String orientationCmdMessage) {
emit(state.copyWith(orientationCmdFlag: orientationCmdFlag, orientationCmdMessage: orientationCmdMessage));
}
void getOrientation(BuildContext context) async {
final Map<String, dynamic> data = json.decode(state.orientationCmdMessage);
H5Message h5Message = H5Message.fromJson(data);
setOrientationCmdFlag(false, '');
final orientation = MediaQuery.of(context).orientation;
var resp = {
'unique': h5Message.unique,
'cmd': h5Message.cmd,
'data': {'orientation': orientation == Orientation.portrait ? "portrait" : "landscape"},
'errMsg': '',
};
_sendResponse(resp);
}
void setWindowInfoCmdFlag(bool windowInfoCmdFlag, String windowInfoCmdMessage) {
emit(state.copyWith(windowInfoCmdFlag: windowInfoCmdFlag, windowInfoCmdMessage: windowInfoCmdMessage));
}
void getWindowInfo(BuildContext context) async {
final Map<String, dynamic> data = json.decode(state.windowInfoCmdMessage);
H5Message h5Message = H5Message.fromJson(data);
setWindowInfoCmdFlag(false, '');
final mediaQuery = MediaQuery.of(context);
final viewPadding = mediaQuery.viewPadding;
final size = mediaQuery.size;
final safeArea = mediaQuery.padding;
final devicePixelRatio = mediaQuery.devicePixelRatio;
// 计算安全区域坐标
final safeAreaLeft = safeArea.left;
final safeAreaRight = size.width - safeArea.right;
final safeAreaTop = safeArea.top;
final safeAreaBottom = size.height - safeArea.bottom;
final safeAreaWidth = size.width - safeArea.horizontal;
final safeAreaHeight = size.height - safeArea.vertical;
final windowInfo = {
'pixelRatio': devicePixelRatio,
'screenWidth': size.width * devicePixelRatio,
'screenHeight': size.height * devicePixelRatio,
'windowWidth': size.width,
'windowHeight': size.height,
'statusBarHeight': viewPadding.top,
'screenTop': 0, // Flutter中通常不使用此值,设为0
'safeArea': {
'left': safeAreaLeft,
'right': safeAreaRight,
'top': safeAreaTop,
'bottom': safeAreaBottom,
'width': safeAreaWidth,
'height': safeAreaHeight,
},
};
var resp = {'unique': h5Message.unique, 'cmd': h5Message.cmd, 'data': windowInfo, 'errMsg': ''};
_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
Future<void> close() async {
_server.close();
// _fluwx.removeSubscriber(_responseListener);
// closeLocalRecorder();
// closeLocalPlayer();
await _playerService.close();
await _recorderService.close();
// try {
// await _recorder?.closeRecorder();
// _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();
}
}