talk_repository.dart 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:dio/dio.dart';
  4. import 'package:electronic_assistant/data/api/atmob_api.dart';
  5. import 'package:electronic_assistant/data/api/atmob_file_api.dart';
  6. import 'package:electronic_assistant/data/api/atmob_stream_api.dart';
  7. import 'package:electronic_assistant/data/api/request/talk_create_request.dart';
  8. import 'package:electronic_assistant/data/api/request/talk_delete_request.dart';
  9. import 'package:electronic_assistant/data/api/request/talk_file_request.dart';
  10. import 'package:electronic_assistant/data/api/request/talk_translate_request.dart';
  11. import 'package:flutter_foreground_task/flutter_foreground_task.dart';
  12. import 'package:get/get.dart';
  13. import 'package:get/get_connect/http/src/request/request.dart';
  14. import 'package:path_provider/path_provider.dart';
  15. import '../../base/base_response.dart';
  16. import '../../dialog/talk_share_dialog.dart';
  17. import '../../utils/foreground_util.dart';
  18. import '../../utils/http_handler.dart';
  19. import '../api/request/talk_export_request.dart';
  20. import '../api/request/talk_generate_request.dart';
  21. import '../api/request/talk_paginate_request.dart';
  22. import '../api/request/talk_rename_request.dart';
  23. import '../api/request/talk_request.dart';
  24. import '../api/request/talk_summary_generate_request.dart';
  25. import '../api/response/talk_check_electric_response.dart';
  26. import '../api/response/talk_info_response.dart';
  27. import '../api/response/talk_paginate_response.dart';
  28. import '../api/response/talk_translate_response.dart';
  29. import '../bean/talk_original.dart';
  30. import '../bean/talks.dart';
  31. import 'account_repository.dart';
  32. class TalkRepository {
  33. TalkRepository._();
  34. final Set<String> _uploadingTalkIds = {};
  35. final Map<String, RxDouble> _uploadingTalkProgress = {};
  36. final _talkList = RxList<TalkBean>();
  37. RxList<TalkBean> get talkList => _talkList;
  38. Future<TalkBean> talkSummaryGenerate(String id, int templateId) {
  39. return atmobApi
  40. .talkSummaryGenerate(TalkSummaryGenerateRequest(id, templateId))
  41. .then(HttpHandler.handle(false));
  42. }
  43. Future<TalkTranslateResponse> talkTranslate(String content) {
  44. return atmobApi
  45. .talkTranslate(TalkTranslateRequest(content))
  46. .then(HttpHandler.handle(false));
  47. }
  48. bool isUploadingTalk(String talkId) {
  49. return _uploadingTalkIds.contains(talkId);
  50. }
  51. void renovateTalkData(TalkBean talkInfo) {
  52. for (int i = 0; i < _talkList.length; i++) {
  53. if (_talkList[i].id == talkInfo.id) {
  54. _talkList[i].updateBean(talkInfo);
  55. break;
  56. }
  57. }
  58. }
  59. Future<File> talkExport(
  60. String talkId, String fileName, ShareTalkType type) async {
  61. ResponseBody responseBody = await atmobStreamApi.talkExportFile(
  62. TalkExportRequest(talkId, type == ShareTalkType.summary ? 1 : 2));
  63. List<String>? contentType = responseBody.headers['Content-Type'];
  64. if (contentType != null) {
  65. for (var value in contentType) {
  66. if (value.contains('application/json')) {
  67. BaseResponse<String> baseResponse = BaseResponse.fromJson(
  68. jsonDecode(await responseBody.stream
  69. .map((bytes) => utf8.decoder.convert(bytes))
  70. .toList()
  71. .then((value) => value.join())),
  72. (json) => json as String);
  73. throw ServerErrorException(baseResponse.code, baseResponse.message);
  74. } else {
  75. final directory = await getTemporaryDirectory();
  76. final filePath = '${directory.path}/export/$fileName';
  77. final file = File(filePath);
  78. if (!await file.exists()) {
  79. await file.create(recursive: true);
  80. }
  81. await file.writeAsBytes(await responseBody.stream.toBytes());
  82. return file;
  83. }
  84. }
  85. }
  86. throw Exception('Invalid content type');
  87. }
  88. void setTalkList(List<TalkBean> list) {
  89. _talkList.assignAll(list);
  90. }
  91. void addNewTalkData(TalkBean talkInfo) {
  92. _talkList.insert(0, talkInfo);
  93. }
  94. clearTalkList() {
  95. _talkList.clear();
  96. }
  97. Future<TalkPaginateResponse> refreshHomeTalkData({int? sortType = 1}) {
  98. int limit;
  99. if (_talkList.isEmpty || _talkList.length < 10) {
  100. limit = 10;
  101. } else {
  102. limit = _talkList.length;
  103. }
  104. return requestTalkPagePaginate(0, limit,
  105. sortType: sortType, isClearAll: true);
  106. }
  107. Future<TalkPaginateResponse> requestTalkPagePaginate(int offset, int limit,
  108. {String? searchKeyword, int? sortType = 1, bool? isClearAll = false}) {
  109. return talkPagePaginate(offset, limit,
  110. searchKeyword: searchKeyword, sortType: sortType)
  111. .then((response) {
  112. if (isClearAll == true) {
  113. _talkList.clear();
  114. }
  115. if (response.list != null) {
  116. _talkList.addAll(response.list!);
  117. }
  118. return response;
  119. });
  120. }
  121. ///sortType 1:按创建时间倒序 2:按更新时间倒序
  122. Future<TalkPaginateResponse> talkPagePaginate(int offset, int limit,
  123. {String? searchKeyword, int? sortType = 1}) {
  124. return atmobApi
  125. .talkPagePaginate(TalkPaginateRequest(offset, limit,
  126. searchKeyword: searchKeyword, sortType: sortType))
  127. .then(HttpHandler.handle(false));
  128. }
  129. Future<List<TalkOriginal>> talkOriginal(String? talkId) {
  130. return atmobApi
  131. .talkOriginal(
  132. TalkRequest(talkId, isExample: !accountRepository.isLogin.value))
  133. .then(HttpHandler.handle(false))
  134. .then((data) {
  135. if (data.list != null) {
  136. return data.list!;
  137. } else {
  138. return [];
  139. }
  140. });
  141. }
  142. // duration 音频时长,单位为秒
  143. Future<TalkCheckElectricResponse> checkElectric(double duration) {
  144. return atmobApi
  145. .checkElectric(TalkGenerateRequest(duration))
  146. .then(HttpHandler.handle(false));
  147. }
  148. Future<TalkInfoResponse> talkInfo(String id) {
  149. return atmobApi
  150. .talkInfo(TalkRequest(id, isExample: !accountRepository.isLogin.value))
  151. .then(HttpHandler.handle(true));
  152. }
  153. Future<void> talkRename(String? id, String? title) {
  154. return atmobApi
  155. .talkRename(TalkRenameRequest(id, title))
  156. .then(HttpHandler.handle(true));
  157. }
  158. Future<void> talkDelete(String? id) {
  159. return atmobApi
  160. .talkDelete(TalkDeleteRequest(id))
  161. .then(HttpHandler.handle(true));
  162. }
  163. Future<TalkBean> talkCreate(String requestId, int duration,
  164. {String? localAudioUrl, FileUploadType? uploadType}) {
  165. return atmobApi
  166. .talkCreate(TalkCreateRequest(duration, requestId,
  167. localAudioUrl: localAudioUrl, uploadType: uploadType?.value))
  168. .then(HttpHandler.handle(true))
  169. .then((bean) {
  170. //添加新的录音到最新记录
  171. talkRepository.addNewTalkData(bean);
  172. return bean;
  173. });
  174. }
  175. Future<String> uploadTalkFile(String talkId, double duration, File file) {
  176. _uploadingTalkIds.add(talkId);
  177. startForegroundService(
  178. serviceId: talkId.hashCode,
  179. notificationTitle: '正在上传录音',
  180. notificationText: '请勿关闭应用',
  181. callback: setUploadCallback);
  182. RxDouble progressRx = getUploadProgress(talkId);
  183. return atmobFileApi
  184. .uploadTalkFile(TalkFileRequest(talkId, duration, file: file).toJson(),
  185. onSendProgress: (count, total) {
  186. progressRx.value = count / total;
  187. })
  188. .then(HttpHandler.handle(true))
  189. .then((response) {
  190. _uploadingTalkIds.remove(talkId);
  191. return response.taskId;
  192. })
  193. .catchError((error) {
  194. _uploadingTalkIds.remove(talkId);
  195. throw error;
  196. })
  197. .whenComplete(() {
  198. stopForegroundService();
  199. });
  200. }
  201. RxDouble getUploadProgress(String talkId) {
  202. if (_uploadingTalkProgress[talkId] == null) {
  203. _uploadingTalkProgress[talkId] = RxDouble(0);
  204. }
  205. return _uploadingTalkProgress[talkId]!;
  206. }
  207. }
  208. class UploadTaskHandler extends TaskHandler {
  209. @override
  210. Future<void> onDestroy(DateTime timestamp) {
  211. // TODO: implement onDestroy
  212. return Future.value();
  213. }
  214. @override
  215. void onRepeatEvent(DateTime timestamp) {
  216. // TODO: implement onRepeatEvent
  217. }
  218. @override
  219. Future<void> onStart(DateTime timestamp, TaskStarter starter) {
  220. // TODO: implement onStart
  221. return Future.value();
  222. }
  223. }
  224. @pragma('vm:entry-point')
  225. void setUploadCallback() {
  226. // The setTaskHandler function must be called to handle the task in the background.
  227. FlutterForegroundTask.setTaskHandler(UploadTaskHandler());
  228. }
  229. enum FileUploadType {
  230. record(0),
  231. local(1);
  232. final int value;
  233. const FileUploadType(this.value);
  234. }
  235. final talkRepository = TalkRepository._();