web_cubit.dart
12 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
import 'dart:async';
import 'dart:convert';
import 'dart:io';
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/local_server_service.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:fluwx/fluwx.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:uuid/uuid.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebState extends Equatable {
final bool loaded;
final String title;
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;
const WebState({
this.loaded = false,
this.title = '界面加载中...',
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 = '',
});
WebState copyWith({
bool? loaded,
String? title,
String? ip,
String? sessionCode,
String? userCode,
String? classCode,
int? userType,
String? stuId,
bool? recorderIsInit,
int? recordState,
String? recordPath,
bool? playerIsInit,
int? playState,
String? playId,
}) {
return WebState(
loaded: loaded ?? this.loaded,
title: title ?? this.title,
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,
);
}
@override
List<Object?> get props => [
loaded,
title,
ip,
sessionCode,
userCode,
classCode,
userType,
stuId,
recorderIsInit,
recordState,
recordPath,
playerIsInit,
playState,
playId,
];
}
class WebCubit extends Cubit<WebState> {
late final MessageDispatcher _dispatcher;
late final WebViewController _controller;
late final HttpServer _server;
late final Fluwx _fluwx;
FlutterSoundRecorder? _recorder;
FlutterSoundPlayer? _player;
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) {
// 进行新页面加载时,关闭录音器和播放器,(如果有打开过)
// closeLocalRecorder();
// closeLocalPlayer();
},
onPageFinished: (String url) {
controller.runJavaScript(
'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")',
);
finishLoading();
print('onPageFinished--------------------------------->');
print(url);
},
),
)
..addJavaScriptChannel("xeJsBridge", onMessageReceived: _onMessageReceived);
// 启动本地服务器,并加载HTML
_startLocalServerAndLoadHtml();
_fluwx = getIt.get<Fluwx>();
}
_startLocalServerAndLoadHtml() async {
// 启动本地服务器
_server = await LocalServerService().startLocalServer();
final String serverUrl;
if (state.sessionCode == null || state.sessionCode == '') {
// serverUrl = 'http://${state.ip}:${_server.port}/test/test.html';
serverUrl = 'http://127.0.0.1:${_server.port}/test/test.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}';
// serverUrl =
// 'http://localdev.banxiaoer.net/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));
}
_onMessageReceived(JavaScriptMessage message) async {
try {
final Map<String, dynamic> data = json.decode(message.message);
H5Message h5Message = H5Message.fromJson(data);
_dispatcher.dispatch(h5Message, (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: '班小二测试H5'));
}
// 测试
void setTitle(String title) {
emit(state.copyWith(title: title));
}
// 测试
void resetLoading() {
emit(state.copyWith(loaded: false, title: '界面加载中...'));
}
//测试
void goWechatAuth() {
router.go('/wechatAuth');
}
//测试
void goAuth() {
String serverUrl = 'http://${state.ip}:${_server.port}/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,
),
);
}
// 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 {
if (await _controller.canGoBack()) {
_controller.goBack();
}
}
/// 录音初始化
Future<bool> _initRecorder() async {
// 请求麦克风权限
var status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw RecordingPermissionException('麦克风权限未授权!');
}
if (state.recordState != 0) {
return false;
}
final directory = await getTemporaryDirectory();
String recordPath = '${directory.path}/${Uuid().v5(Namespace.url.value, 'www.banxiaoer.com')}_record.aac';
// 打开录音器
try {
final recorder = FlutterSoundRecorder();
_recorder = (await recorder.openRecorder())!;
emit(state.copyWith(recorderIsInit: true, recordPath: recordPath));
return true;
} catch (e) {
throw Exception('打开录音器失败!');
}
}
/// 开始录音
Future<bool> startRecording() async {
if (state.recorderIsInit) {
return false;
}
if (state.recordState != 0) {
return false;
}
final initResult = await _initRecorder();
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;
}
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;
}
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) {
throw Exception("录音器状态错误");
}
var url = await _recorder!.stopRecorder();
await _recorder!.closeRecorder();
if (url == null || url.isEmpty) {
throw Exception("录音失败");
}
emit(state.copyWith(recorderIsInit: false, recordState: 0, recordPath: ''));
return {'url': url};
}
/// 清空录音
Future<bool> clearRecording() async {
// await _recorder!.stopRecorder();
await _recorder!.closeRecorder();
emit(state.copyWith(recorderIsInit: false, recordState: 0, recordPath: ''));
return true;
}
/// 播放初始化
Future<bool> _initPlayer() async {
// 打开播放器
try {
final player = FlutterSoundPlayer();
_player = (await player.openPlayer())!;
emit(state.copyWith(playerIsInit: true));
return true;
} catch (e) {
throw Exception('打开播放器失败!');
}
}
/// 播放音频
Future<bool> playAudio(String url) async {
if (!state.playerIsInit) {
final initResult = await _initPlayer();
if (!initResult) {
return false;
}
}
await _player!.startPlayer(
fromURI: url,
whenFinished: () async {
await _player!.stopPlayer();
emit(state.copyWith(playState: 0));
},
);
emit(state.copyWith(playState: 1));
return true;
}
/// 暂停播放
Future<bool> pauseAudio() async {
if (!state.playerIsInit) {
throw Exception("播放器未初始化");
}
if (state.playState != 1) {
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("播放器状态错误");
}
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) {
throw Exception("播放器状态错误");
}
await _player!.stopPlayer();
emit(state.copyWith(playState: 0));
return true;
}
/// 清空播放
Future<bool> clearAudio() async {
await _player?.closePlayer();
emit(state.copyWith(playerIsInit: false, playState: 0, playId: ''));
return true;
}
@override
Future<void> close() async {
_server.close();
// _fluwx.removeSubscriber(_responseListener);
// closeLocalRecorder();
// closeLocalPlayer();
await _recorder?.closeRecorder();
await _player?.closePlayer();
return super.close();
}
}