web_cubit.dart
21 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
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:appframe/services/recorder_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;
/// 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.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? 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,
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,
orientationCmdFlag,
orientationCmdMessage,
windowInfoCmdFlag,
windowInfoCmdMessage,
chooseImageCmdFlag,
chooseImageCmdMessage,
chooseVideoCmdFlag,
chooseVideoCmdMessage,
];
}
class WebCubit extends Cubit<WebState> {
late final MessageDispatcher _dispatcher;
late final WebViewController _controller;
late final Fluwx _fluwx;
HttpServer? _server;
PlayerService? _playerService;
RecorderService? _recorderService;
WebViewController get controller => _controller;
WebCubit(super.initialState) {
// 没有登录数据,跳转到登录页面
if (state.sessionCode == null || state.sessionCode == '') {
WidgetsBinding.instance.addPostFrameCallback((_) {
router.go('/loginMain');
});
} else {
_init();
}
}
Future<void> _init() async {
// 消息处理器
_dispatcher = MessageDispatcher();
// 启动本地服务器
await _startLocalServer();
// 创建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(
onUrlChange: (UrlChange url) {},
onPageStarted: (String url) async {
// 进行新页面加载时,关闭录音器和播放器,(如果有打开过)
await _playerService?.close();
await _recorderService?.close();
},
onPageFinished: (String url) async {
print('onPageFinished--------------------------------->');
print(url);
/*if (url == '${Constant.localServerTestFileUrl}/login.html') {
return;
}*/
_controller.runJavaScript(
'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")',
);
finishLoading();
},
),
);
await _controller.addJavaScriptChannel("xeJsBridge", onMessageReceived: _onMessageReceived);
}
void _loadHtml() {
// 构造函数中已拦截判断未登录的情况进行了处理,所以这里不再处理未登录的情况
final String 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));
}
Future<void> _loginIM() async {
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 登录失败");
}
}
}
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));
}
//测试
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);
}
@override
Future<void> close() async {
_server?.close();
// _fluwx.removeSubscriber(_responseListener);
await _playerService?.close();
await _recorderService?.close();
return super.close();
}
}