talk_repository.dart 8.5 KB

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