talk_repository.dart 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. for (int i = 0; i < _talkList.length; i++) {
  94. if (_talkList[i].id == talkInfo.id) {
  95. _talkList[i].updateBean(talkInfo);
  96. return;
  97. }
  98. }
  99. _talkList.insert(0, talkInfo);
  100. }
  101. clearTalkList() {
  102. _talkList.clear();
  103. }
  104. Future<TalkPaginateResponse> refreshHomeTalkData({int? sortType = 1}) {
  105. int limit;
  106. if (_talkList.isEmpty || _talkList.length < homeMaxShowCount) {
  107. limit = homeMaxShowCount;
  108. } else {
  109. limit = _talkList.length;
  110. }
  111. return requestTalkPagePaginate(0, limit,
  112. sortType: sortType, isClearAll: true);
  113. }
  114. Future<TalkPaginateResponse> requestTalkPagePaginate(int offset, int limit,
  115. {String? searchKeyword, int? sortType = 1, bool? isClearAll = false}) {
  116. return talkPagePaginate(offset, limit,
  117. searchKeyword: searchKeyword, sortType: sortType)
  118. .then((response) {
  119. if (isClearAll == true) {
  120. _talkList.clear();
  121. }
  122. if (response.list != null) {
  123. _talkList.addAll(response.list!);
  124. }
  125. return response;
  126. });
  127. }
  128. ///sortType 1:按创建时间倒序 2:按更新时间倒序
  129. Future<TalkPaginateResponse> talkPagePaginate(int offset, int limit,
  130. {String? searchKeyword, int? sortType = 1}) {
  131. return atmobApi
  132. .talkPagePaginate(TalkPaginateRequest(offset, limit,
  133. searchKeyword: searchKeyword, sortType: sortType))
  134. .then(HttpHandler.handle(false));
  135. }
  136. Future<List<TalkOriginal>> talkOriginal(String? talkId) {
  137. return atmobApi
  138. .talkOriginal(
  139. TalkRequest(talkId, isExample: !accountRepository.isLogin.value))
  140. .then(HttpHandler.handle(false))
  141. .then((data) {
  142. if (data.list != null) {
  143. return data.list!;
  144. } else {
  145. return [];
  146. }
  147. });
  148. }
  149. // duration 音频时长,单位为秒
  150. Future<TalkCheckElectricResponse> checkElectric(double duration) {
  151. return atmobApi
  152. .checkElectric(TalkGenerateRequest(duration))
  153. .then(HttpHandler.handle(false));
  154. }
  155. Future<TalkInfoResponse> talkInfo(String id) {
  156. return atmobApi
  157. .talkInfo(TalkRequest(id, isExample: !accountRepository.isLogin.value))
  158. .then(HttpHandler.handle(true));
  159. }
  160. Future<void> talkRename(String? id, String? title) {
  161. return atmobApi
  162. .talkRename(TalkRenameRequest(id, title))
  163. .then(HttpHandler.handle(true));
  164. }
  165. Future<void> talkDelete(String? id) {
  166. return atmobApi
  167. .talkDelete(TalkDeleteRequest(id))
  168. .then(HttpHandler.handle(true));
  169. }
  170. Future<TalkBean> talkCreate(String requestId, int duration,
  171. {String? localAudioUrl, FileUploadType? uploadType}) {
  172. return atmobApi
  173. .talkCreate(TalkCreateRequest(duration, requestId,
  174. localAudioUrl: localAudioUrl, uploadType: uploadType?.value))
  175. .then(HttpHandler.handle(true))
  176. .then((bean) {
  177. //添加新的录音到最新记录
  178. talkRepository.addNewTalkData(bean);
  179. return bean;
  180. });
  181. }
  182. Future<String> uploadTalkFile(String talkId, double duration, File file) {
  183. _uploadingTalkIds.add(talkId);
  184. startForegroundService(
  185. serviceId: talkId.hashCode,
  186. notificationTitle: '正在上传录音',
  187. notificationText: '请勿关闭应用',
  188. callback: setUploadCallback);
  189. RxDouble progressRx = getUploadProgress(talkId);
  190. return atmobFileApi
  191. .uploadTalkFile(TalkFileRequest(talkId, duration, file: file).toJson(),
  192. onSendProgress: (count, total) {
  193. progressRx.value = count / total;
  194. })
  195. .then(HttpHandler.handle(true))
  196. .then((response) {
  197. _uploadingTalkIds.remove(talkId);
  198. return response.taskId;
  199. })
  200. .catchError((error) {
  201. _uploadingTalkIds.remove(talkId);
  202. throw error;
  203. })
  204. .whenComplete(() {
  205. stopForegroundService();
  206. });
  207. }
  208. RxDouble getUploadProgress(String talkId) {
  209. if (_uploadingTalkProgress[talkId] == null) {
  210. _uploadingTalkProgress[talkId] = RxDouble(0);
  211. }
  212. return _uploadingTalkProgress[talkId]!;
  213. }
  214. }
  215. class UploadTaskHandler extends TaskHandler {
  216. @override
  217. Future<void> onDestroy(DateTime timestamp) {
  218. // TODO: implement onDestroy
  219. return Future.value();
  220. }
  221. @override
  222. void onRepeatEvent(DateTime timestamp) {
  223. // TODO: implement onRepeatEvent
  224. }
  225. @override
  226. Future<void> onStart(DateTime timestamp, TaskStarter starter) {
  227. // TODO: implement onStart
  228. return Future.value();
  229. }
  230. }
  231. @pragma('vm:entry-point')
  232. void setUploadCallback() {
  233. // The setTaskHandler function must be called to handle the task in the background.
  234. FlutterForegroundTask.setTaskHandler(UploadTaskHandler());
  235. }
  236. enum FileUploadType {
  237. record(0),
  238. local(1);
  239. final int value;
  240. const FileUploadType(this.value);
  241. }
  242. final talkRepository = TalkRepository._();