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