api.dart 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import 'dart:async';
  2. import 'dart:core';
  3. import 'dart:typed_data';
  4. import 'package:app_business/app_config.dart';
  5. import 'package:app_business/generated/base.pb.dart' as pb;
  6. import 'package:app_business/generated/google/protobuf/duration.pb.dart' as pb;
  7. import 'package:app_business/generated/google/protobuf/timestamp.pb.dart' as pb;
  8. import 'package:app_business/generated/track_offical.pbgrpc.dart' as pb;
  9. import 'package:app_business/service/app.dart';
  10. import 'package:grpc/grpc.dart';
  11. import 'package:track_common/model.dart';
  12. import 'package:track_common/track_common.dart';
  13. import 'abase.dart';
  14. export 'package:app_business/generated/base.pb.dart'
  15. show DefaultRequest, IdRequest, IdArrRequest;
  16. export 'package:app_business/generated/google/protobuf/timestamp.pb.dart';
  17. export 'package:app_business/generated/track_offical.pbgrpc.dart'
  18. show
  19. ToMatchRegusterAddRequest,
  20. ToMatchRegusterListRequest,
  21. ToMatchRegusterIsAllowChackEditRequest;
  22. export 'package:fixnum/fixnum.dart' show Int64;
  23. typedef SmsType = pb.SmsType;
  24. extension _ImageExt on pb.NetImage {
  25. NetImage toModel() {
  26. return NetImage(url, md5);
  27. }
  28. }
  29. extension DateTimeExt on DateTime? {
  30. pb.Timestamp toPb() {
  31. if (this != null) {
  32. return pb.Timestamp.fromDateTime(this!.toUtc());
  33. } else {
  34. return pb.Timestamp();
  35. }
  36. }
  37. }
  38. extension TSExt on pb.Timestamp {
  39. DateTime toModel() {
  40. return toDateTime(toLocal: true);
  41. }
  42. }
  43. extension DurationExt on pb.Duration {
  44. Duration toModel() {
  45. final microseconds = hasNanos() ? nanos / 1000 : 0;
  46. return Duration(
  47. seconds: seconds.toInt(), microseconds: microseconds.toInt());
  48. }
  49. }
  50. extension PositionExt on pb.Position {
  51. Position toModel() {
  52. return Position(latitude: latitude, longitude: longitude)
  53. ..altitude = altitude;
  54. }
  55. }
  56. extension PBToControlPointExt on pb.ToControlPoint {
  57. ControlPoint toModel() {
  58. final one = ControlPoint()
  59. ..areaId = sn
  60. ..intId = id
  61. ..isSuccess = isCheckSuccess
  62. ..sn = orderNo.toString()
  63. ..checkAfterPrev = checkAfterLast.toModel()
  64. ..checkAfterStart = checkAfterStart.toModel()
  65. ..checkDistanceAfterPrev = disAfterLast.meter
  66. ..distanceStraightToPrev = disStraightAfterLast.meter
  67. ..paceAfterPrev = Pace.perKm(paceAfterLast.seconds)
  68. ..paceAfterStart = Pace.perKm(paceAfterStart.seconds)
  69. ..position = ciPosition.toModel();
  70. if (cType == pb.CType.BeginType) {
  71. one.isStart = true;
  72. }
  73. if (cType == pb.CType.EndType) {
  74. one.isFinish = true;
  75. }
  76. return one;
  77. }
  78. }
  79. class ApiService extends IService {
  80. ClientChannel? channel;
  81. @override
  82. Future<void> init() async {
  83. channel = _newChannel();
  84. }
  85. ClientChannel _newChannel() {
  86. return ClientChannel(
  87. AppConfig.apiHost,
  88. port: AppConfig.apiPort,
  89. options: const ChannelOptions(credentials: ChannelCredentials.secure()
  90. // ChannelCredentials.insecure()
  91. ),
  92. );
  93. }
  94. pb.ApiToClient get stub {
  95. return _newStub(timeout: 10.seconds);
  96. }
  97. pb.ApiToClient _newStub({Duration? timeout, ClientChannel? channel}) {
  98. if (this.channel == null) {
  99. throw Exception('$runtimeType 未初始化');
  100. }
  101. final metadata = <String, String>{};
  102. metadata['version'] = _appVersion;
  103. if (token != null) {
  104. metadata['token'] = token!;
  105. }
  106. // debug("token: $token");
  107. return pb.ApiToClient(channel ?? this.channel!,
  108. options: CallOptions(
  109. metadata: metadata,
  110. timeout: timeout,
  111. ));
  112. }
  113. String get _appVersion => Get.find<AppService>().appVersion;
  114. set token(String? v) {
  115. Get.find<AppService>().token.val = v ?? '';
  116. }
  117. String? get token {
  118. final app = Get.find<AppService>();
  119. final token = app.token.val;
  120. if (token.isEmpty) {
  121. return null;
  122. }
  123. return token;
  124. }
  125. // 获取短信验证码
  126. Future<void> authSendCodeToPhone(String phone, SmsType smsType) async {
  127. info('authSendCodeToPhone [$phone]');
  128. await stub.toSendCodeToPhoneV2(pb.ToSendCodeToPhoneRequestV2()
  129. ..phone = phone
  130. ..smsType = smsType);
  131. }
  132. // 场控端_登录
  133. Future<void> signIn(String userCode, String password, String ip) async {
  134. final r = await stub.toSignInV2(pb.ToSignInRequestV2()
  135. ..userCode = userCode
  136. ..password = password
  137. ..ip = ip);
  138. token = r.token;
  139. debug('sign in success: $token');
  140. }
  141. // 场控端_登出
  142. void signOut() {
  143. stub.toSignOutV2(pb.DefaultRequest());
  144. token = null;
  145. }
  146. Future<Duration> getSmsSendLeftTime(String phone) async {
  147. final r = await stub
  148. .toGetSmsSendLeftTimeV2(pb.GetSmsSendLeftTimeRequest()..phone = phone);
  149. info('getSmsSendLeftTime: $phone - ${r.second}s');
  150. return r.second.seconds;
  151. }
  152. Future<List<MapInfo>> getMapList(int limit, int offset) async {
  153. final r = await stub.toMapListV2(pb.MapListRequestV2()
  154. ..limit = limit
  155. ..offset = offset);
  156. return r.list
  157. .map((e) => MapInfo(e.mapId, e.name, e.distance.meter, e.description,
  158. e.mapScaleNumber, e.image.toModel()))
  159. .toList();
  160. }
  161. Future<BinReader> getBinReaderByMd5(Uint8List md5) async {
  162. final stream =
  163. stub.toGetBinaryByMd5(pb.ToGetBinaryByMd5Request()..md5 = md5);
  164. final controller = StreamController<List<int>>();
  165. controller.onCancel = () {
  166. stream.cancel();
  167. };
  168. Future<void> rcv() async {
  169. try {
  170. await for (final one in stream) {
  171. controller.add(one.data);
  172. }
  173. } finally {
  174. controller.close();
  175. stream.cancel();
  176. }
  177. }
  178. rcv();
  179. stream.headers.then((value) => debug(value));
  180. final headers = await stream.headers;
  181. final lenStr = headers['all-length']!;
  182. final length = int.parse(lenStr);
  183. final nonce = headers['nonce']!;
  184. final ext = headers['ext']!;
  185. return BinReader(
  186. data: controller.stream, length: length, ext: ext, nonce: nonce);
  187. }
  188. Future<void> eventEdit(int id, EventRegisterInfo event) async {
  189. await stub.toMatchRegusterEdit(pb.ToMatchRegusterEditRequest()
  190. ..id = id
  191. ..regName = event.name
  192. ..startAt = event.eventStartAt.toPb()
  193. ..stopAt = event.eventStopAt.toPb()
  194. ..bShowTime = event.showStartAt.toPb()
  195. ..eShowTime = event.showStopAt.toPb()
  196. ..isQueryPwd = event.passwordQuery != null
  197. ..queryPasswd = event.passwordQuery ?? '');
  198. }
  199. Future<void> eventUserAllocRoute(int checkId, int routeId) async {
  200. await stub.toCourseChackMatch(pb.ToCourseChackMatchRequest()
  201. ..id = checkId
  202. ..cId = routeId);
  203. }
  204. Future<void> eventUserAllocRouteAll(Iterable<int> checkIdList) async {
  205. await stub
  206. .allCourseChackMatch(pb.IdArrRequest()..idArr.addAll(checkIdList));
  207. }
  208. Future<void> eventUserStartAll(Iterable<int> checkIdList) async {
  209. await stub
  210. .allMatchChackInsStart(pb.IdArrRequest()..idArr.addAll(checkIdList));
  211. }
  212. Future<void> eventUserRestartAll(Iterable<int> checkIdList) async {
  213. await stub.allMatchChackInsForceResume(
  214. pb.IdArrRequest()..idArr.addAll(checkIdList));
  215. }
  216. Future<void> eventUserDelAll(Iterable<int> checkIdList) async {
  217. await stub
  218. .allMatchChackInsDel(pb.IdArrRequest()..idArr.addAll(checkIdList));
  219. }
  220. Future<void> eventSettingsRulesSave(Iterable<Rule> rules) async {
  221. await stub.toActivityRulesSave(pb.ToActivityRulesSaveRequest()
  222. ..list.addAll(rules.map((e) {
  223. final one = pb.ToActivityRulesSaveInfo()
  224. ..arrId = e.id
  225. ..isLock = e.isAppLock;
  226. final vt = e.value;
  227. if (vt is RuleValueBool) {
  228. one.arValue = vt.value ? 'true' : 'false';
  229. }
  230. if (vt is RuleValueArrStr) {
  231. one.arValue = vt.value;
  232. }
  233. return one;
  234. })));
  235. }
  236. Stream<CooperationInfo> cooperationInfo() async* {
  237. while (true) {
  238. await 1.seconds.delay();
  239. try {
  240. final r = await stub.toCooperationQuery(pb.DefaultRequest());
  241. yield CooperationInfo()
  242. ..name = r.name
  243. ..leftCount = r.leftMatchNum;
  244. } catch (e) {
  245. warn('获取可用数错误', e);
  246. }
  247. }
  248. }
  249. }
  250. class CooperationInfo {
  251. var name = '';
  252. // 可用数
  253. var leftCount = 0;
  254. }
  255. class EventRegisterInfo {
  256. var id = 0;
  257. var name = '';
  258. var showStartAt = DateTime.now();
  259. var eventStartAt = DateTime.now();
  260. var showStopAt = DateTime.now();
  261. var eventStopAt = DateTime.now();
  262. String? passwordQuery;
  263. String? passwordEvent;
  264. }
  265. class Rule {
  266. var id = 0;
  267. var idx = 0;
  268. var name = '';
  269. var isAppLock = false;
  270. var isAllowEditAppLock = true;
  271. var isLockAll = false;
  272. RuleValue value = RuleValueBool();
  273. }
  274. class RuleValue {}
  275. class RuleValueBool extends RuleValue {
  276. var value = false;
  277. }
  278. class RuleValueArrStr extends RuleValue {
  279. var value = '';
  280. var options = <RuleValueArrStrOption>[];
  281. }
  282. class RuleValueArrStrOption {
  283. var show = '';
  284. var value = '';
  285. }