talk_repository.dart 8.0 KB

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