talk_repository.dart 8.3 KB

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