controller.dart 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:electronic_assistant/base/base_controller.dart';
  4. import 'package:electronic_assistant/data/repositories/task_repository.dart';
  5. import 'package:electronic_assistant/module/chat/view.dart';
  6. import 'package:electronic_assistant/module/talk/summary/view.dart';
  7. import 'package:electronic_assistant/module/talk/todo/view.dart';
  8. import 'package:electronic_assistant/resource/assets.gen.dart';
  9. import 'package:electronic_assistant/resource/colors.gen.dart';
  10. import 'package:electronic_assistant/resource/string.gen.dart';
  11. import 'package:electronic_assistant/utils/error_handler.dart';
  12. import 'package:electronic_assistant/utils/expand.dart';
  13. import 'package:electronic_assistant/utils/mmkv_util.dart';
  14. import 'package:flutter/cupertino.dart';
  15. import 'package:flutter_screenutil/flutter_screenutil.dart';
  16. import 'package:get/get.dart';
  17. import 'package:connectivity_plus/connectivity_plus.dart';
  18. import '../../data/bean/agenda_list_all_bean.dart';
  19. import '../../data/bean/talks.dart';
  20. import '../../data/repositories/agenda_repository.dart';
  21. import '../../data/repositories/talk_repository.dart';
  22. import '../../dialog/alert_dialog.dart';
  23. import '../../utils/toast_util.dart';
  24. import '../record/controller.dart';
  25. import 'original/view.dart';
  26. import 'package:just_audio/just_audio.dart';
  27. class TalkController extends BaseController {
  28. final String uploadNoPrompts = "UPLOAD_NO_PROMPTS";
  29. final Rxn<TalkBean> talkBean = Rxn();
  30. final isShowElectricLow = false.obs;
  31. bool isAudioLoading = false;
  32. final double sliderMax = 1;
  33. bool? audioFileIsExist;
  34. bool? isUploadedFile;
  35. final isAudioPlaying = false.obs;
  36. final audioProgressValue = 0.0.obs;
  37. final audioDuration = Duration.zero.obs;
  38. final agendaAllList = <AgendaListAllBean>[].obs;
  39. final List<String> tabBeans = [
  40. StringName.talkTabSummary.tr,
  41. StringName.talkTabMyTask.tr,
  42. StringName.talkTabOriginal.tr
  43. ];
  44. final _audioPlayer = AudioPlayer();
  45. StreamSubscription? _talkBeanListener;
  46. final pages = [const SummaryView(), const TodoView(), const OriginalView()];
  47. @override
  48. void onReady() {
  49. super.onReady();
  50. _initAudioPlayer();
  51. _initListener();
  52. _getArguments();
  53. }
  54. void _initAudioPlayer() {
  55. _audioPlayer.playerStateStream.listen((playerState) {
  56. if (playerState.processingState == ProcessingState.loading ||
  57. playerState.processingState == ProcessingState.buffering) {
  58. isAudioLoading = true;
  59. debugPrint('音频load = true');
  60. } else {
  61. debugPrint('音频load = false');
  62. isAudioLoading = false;
  63. if (playerState.processingState == ProcessingState.completed) {
  64. _audioPlayer.stop();
  65. _audioPlayer.seek(Duration.zero);
  66. isAudioPlaying.value = false;
  67. debugPrint('音频 播放结束了');
  68. }
  69. }
  70. isAudioPlaying.value = playerState.playing;
  71. }, onError: (Object e, StackTrace stackTrace) {
  72. debugPrint('音频加载异常 == $e');
  73. });
  74. _audioPlayer.durationStream.listen((duration) {
  75. if (duration != null) {
  76. debugPrint('音频总播放时长 == ${duration.inMilliseconds}');
  77. audioDuration.value = duration;
  78. }
  79. });
  80. _audioPlayer.positionStream.listen((position) {
  81. if (audioDuration.value.inMilliseconds > 0) {
  82. audioProgressValue.value =
  83. (position.inMilliseconds / audioDuration.value.inMilliseconds)
  84. .clamp(0.0, sliderMax);
  85. }
  86. });
  87. }
  88. void _initListener() {
  89. _talkBeanListener = talkBean.listen((bean) {
  90. _dealTalkUpdate(bean);
  91. });
  92. }
  93. void _dealTalkUpdate(TalkBean? bean) async {
  94. String? id = talkBean.value?.id;
  95. if (id == null) {
  96. return;
  97. }
  98. try {
  99. File file = await RecordController.getRecordFile(id);
  100. await _audioPlayer.setAudioSource(AudioSource.uri(file.uri));
  101. audioFileIsExist = true;
  102. } catch (e) {
  103. audioFileIsExist = false;
  104. debugPrint('音频设置异常 == $e');
  105. }
  106. }
  107. void _getArguments() {
  108. if (Get.arguments is TalkBean) {
  109. talkBean.value = Get.arguments as TalkBean;
  110. }
  111. }
  112. void updateProgress(double value) {
  113. final newPosition = Duration(
  114. milliseconds: (value * audioDuration.value.inMilliseconds).toInt());
  115. _audioPlayer.seek(newPosition);
  116. }
  117. void clickPlayAudio() {
  118. if (audioFileIsExist != true) {
  119. ToastUtil.showToast(StringName.talkFileNotFind.tr);
  120. return;
  121. }
  122. if (isAudioLoading) {
  123. ToastUtil.showToast(StringName.talkAudioLoading.tr);
  124. return;
  125. }
  126. if (_audioPlayer.playing) {
  127. _audioPlayer.pause();
  128. isAudioPlaying.value = false;
  129. } else {
  130. _audioPlayer.play();
  131. isAudioPlaying.value = true;
  132. }
  133. }
  134. void _checkFileSizeAndNet() async {
  135. String? id = talkBean.value?.id;
  136. if (id == null) {
  137. return;
  138. }
  139. File file = await RecordController.getRecordFile(id);
  140. if (!file.existsSync()) {
  141. ToastUtil.showToast(StringName.talkUploadFileNotExist.tr);
  142. return;
  143. }
  144. bool isCheckRemind = KVUtil.getBool(uploadNoPrompts, false);
  145. if (isCheckRemind) {
  146. _requestAnalyze(file);
  147. return;
  148. }
  149. //如果文件大小低于250MB 不弹窗提醒
  150. if (file.lengthSync() < 250 * 1024 * 1024) {
  151. _requestAnalyze(file);
  152. return;
  153. }
  154. final List<ConnectivityResult> connectivityResult =
  155. await (Connectivity().checkConnectivity());
  156. if (connectivityResult.contains(ConnectivityResult.wifi)) {
  157. _requestAnalyze(file);
  158. } else {
  159. _showTrafficRemindDialog(file.lengthSync().toReadableSize(),
  160. confirmOnTap: (isCheckRemind) {
  161. if (isCheckRemind) {
  162. KVUtil.putBool(uploadNoPrompts, true);
  163. }
  164. _requestAnalyze(file);
  165. });
  166. }
  167. }
  168. void _showTrafficRemindDialog(String holderTxt,
  169. {void Function(bool isCheckRemind)? confirmOnTap}) {
  170. final remindTrafficConsume = false.obs;
  171. Widget getSelectIcon() {
  172. return Obx(() {
  173. return remindTrafficConsume.value
  174. ? Assets.images.iconSelectTrue.image()
  175. : Assets.images.iconSelectFalse.image();
  176. });
  177. }
  178. Assets.images.iconSelectTrue.image();
  179. EAAlertDialog.show(
  180. contentWidget: Column(
  181. children: [
  182. Text(
  183. StringName.talkTrafficRemindTitle.tr
  184. .replacePlaceholders([holderTxt]),
  185. style:
  186. TextStyle(fontSize: 15.sp, color: ColorName.primaryTextColor),
  187. ),
  188. SizedBox(height: 8.h),
  189. GestureDetector(
  190. onTap: () {
  191. remindTrafficConsume.value = !remindTrafficConsume.value;
  192. },
  193. child: IntrinsicWidth(
  194. child: Row(
  195. children: [
  196. SizedBox(width: 20.w, height: 20.w, child: getSelectIcon()),
  197. SizedBox(width: 5.w),
  198. Text(
  199. StringName.talkTrafficRemindTips.tr,
  200. style: TextStyle(
  201. fontSize: 15.sp, color: ColorName.tertiaryTextColor),
  202. )
  203. ],
  204. ),
  205. ),
  206. )
  207. ],
  208. ),
  209. cancelText: StringName.cancel.tr,
  210. confirmText: StringName.sure.tr,
  211. confirmOnTap: () {
  212. confirmOnTap?.call(remindTrafficConsume.value);
  213. });
  214. }
  215. void checkCanAnalyze() async {
  216. String? id = talkBean.value?.id;
  217. double? duration = talkBean.value?.duration;
  218. if (id == null || duration == null) {
  219. return;
  220. }
  221. talkRepository.checkElectric(duration).then((data) {
  222. if (data.enough) {
  223. //检查网络以及文件大小
  224. _checkFileSizeAndNet();
  225. } else {
  226. ToastUtil.showToast(StringName.talkAnalyseLowToast.tr);
  227. isShowElectricLow.value = true;
  228. }
  229. }).catchError((error) {
  230. ToastUtil.showToast(error);
  231. });
  232. }
  233. void _requestAnalyze(File file) {
  234. String? talkId = talkBean.value?.id;
  235. double? duration = talkBean.value?.duration;
  236. if (talkId == null || duration == null || isUploadedFile == true) {
  237. return;
  238. }
  239. talkRepository.uploadTalkFile(talkId, duration, file).then((taskId) {
  240. ToastUtil.showToast('提交成功,小听正在分析谈话,请稍后');
  241. isUploadedFile = true;
  242. talkBean.value = talkBean.value?.copyWith(
  243. taskId: taskId,
  244. status: TalkStatus.analysing,
  245. );
  246. taskRepository.addTask(taskId);
  247. }).catchError((error) {
  248. ErrorHandler.toastError(error);
  249. });
  250. }
  251. void goElectricStore() {
  252. //TODO 跳转至商店页
  253. }
  254. void refreshAgendaAllData() {
  255. String? id = talkBean.value?.id;
  256. if (id == null || agendaAllList.isNotEmpty) {
  257. return;
  258. }
  259. agendaRepository.agendaListAll(id).then((agenda) {
  260. if (agenda.list != null) {
  261. agendaAllList.value = agenda.list!;
  262. }
  263. });
  264. }
  265. void clickAIAnalysis() {
  266. if (talkBean.value != null) {
  267. ChatPage.startByTalk(talkBean.value!);
  268. }
  269. }
  270. @override
  271. void onClose() {
  272. super.onClose();
  273. _talkBeanListener?.cancel();
  274. _audioPlayer.dispose();
  275. }
  276. }