Hibok
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

1401 wiersze
42 KiB

  1. import 'dart:convert';
  2. import 'package:chat/data/WebData.dart';
  3. import 'package:chat/data/chat_data_mgr.dart';
  4. import 'package:chat/data/constants.dart';
  5. import 'package:chat/data/group_data_mgr.dart';
  6. import 'package:chat/generated/i18n.dart';
  7. import 'package:chat/home/EditData.dart';
  8. import 'package:chat/home/IndexPage.dart';
  9. import 'package:chat/home/MoneyPage.dart';
  10. import 'package:chat/home/SelectSexPage.dart';
  11. import 'package:chat/models/ChatMsg.dart';
  12. import 'package:chat/models/UserInfo.dart';
  13. import 'package:chat/models/daily_bonus.dart';
  14. import 'package:chat/models/money_change.dart';
  15. import 'package:chat/proto/all.pbserver.dart';
  16. import 'package:chat/utils/LoadingDialog.dart';
  17. import 'package:chat/utils/MessageMgr.dart';
  18. import 'package:chat/utils/NetUtil.dart';
  19. import 'package:chat/utils/blacklist_mgr.dart';
  20. import 'package:chat/utils/friend_list_mgr.dart';
  21. import 'package:chat/utils/image_util.dart';
  22. import 'package:chat/utils/local_notification_util.dart';
  23. import 'package:chat/utils/sp_utils.dart';
  24. import 'package:chat/utils/sql_util.dart';
  25. import 'package:chat/utils/user_info_table.dart';
  26. import 'dart:core';
  27. import 'package:dio/dio.dart';
  28. import 'package:flutter/material.dart';
  29. import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
  30. import 'package:oktoast/oktoast.dart';
  31. import 'package:provider/provider.dart';
  32. import 'package:shared_preferences/shared_preferences.dart';
  33. import 'dart:io';
  34. import '../data/UserData.dart';
  35. import '../utils/TokenMgr.dart';
  36. import 'package:http_parser/http_parser.dart';
  37. class HttpUtil {
  38. static HttpUtil _instance;
  39. Dio dio;
  40. BaseOptions options;
  41. //static const String BaseUrl = 'http://192.168.0.223:7001/';
  42. //static const String BaseUrl = 'http://192.168.0.207:9080/';
  43. // static const String BaseUrl = 'http://120.79.107.63:9080/';
  44. //static const String BaseUrl = 'http://192.168.0.177:9016/';
  45. static const String BaseUrl = 'https://datasm.chengyouhd.com/';
  46. static HttpUtil _getInstance() {
  47. if (_instance == null) {
  48. _instance = HttpUtil._();
  49. }
  50. return _instance;
  51. }
  52. factory HttpUtil() => _getInstance();
  53. Map friendCache = {};
  54. HttpUtil._() {
  55. options = BaseOptions(
  56. baseUrl: BaseUrl,
  57. headers: {},
  58. );
  59. dio = new Dio(options);
  60. // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
  61. // (HttpClient client) {
  62. // client.findProxy = (uri) {
  63. // //proxy all request to localhost:8888
  64. // return "PROXY 192.168.0.181:8888";
  65. // };
  66. // client.badCertificateCallback =
  67. // (X509Certificate cert, String host, int port) => true;
  68. // };
  69. dio.interceptors
  70. .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
  71. // Do something before request is sent
  72. return options; //continue
  73. // If you want to resolve the request with some custom data,
  74. // you can return a `Response` object or return `dio.resolve(data)`.
  75. // If you want to reject the request with a error message,
  76. // you can return a `DioError` object or return `dio.reject(errMsg)`
  77. }, onResponse: (Response response) async {
  78. // Do something with response data
  79. return response; // continue
  80. }, onError: (DioError e) async {
  81. // Do something with response error
  82. showToast(I18n.of(Constants.getCurrentContext()).net_error);
  83. return e; //continue
  84. }));
  85. }
  86. Future get(url, {data, options, cancelToken}) async {
  87. print('get请求启动! url:$url ,body: $data');
  88. Response response;
  89. try {
  90. response = await dio.get(
  91. url,
  92. queryParameters: data,
  93. cancelToken: cancelToken,
  94. );
  95. print('get请求成功!$url');
  96. } on DioError catch (e) {
  97. if (CancelToken.isCancel(e)) {
  98. print('get请求取消! ' + e.message);
  99. }
  100. print('get请求发生错误:$e');
  101. }
  102. return response;
  103. }
  104. getFriendList(callback) async {
  105. Map data = {
  106. "userId": UserData().basicInfo.userId,
  107. };
  108. data['sign'] = TokenMgr().getSign(data);
  109. Response res = await HttpUtil().post('friendship/friends/list', data: data);
  110. Map resData = res.data;
  111. if (resData['code'] == 0) {
  112. if (callback != null) callback(resData['data']);
  113. }
  114. }
  115. Future getDataWX(url, {data, options, cancelToken}) async {
  116. print('get请求启动! url:$url ,body: $data');
  117. Response response;
  118. BaseOptions options = BaseOptions(
  119. headers: {},
  120. );
  121. Dio dio = new Dio(options);
  122. try {
  123. response = await dio.get(
  124. url,
  125. queryParameters: data,
  126. cancelToken: cancelToken,
  127. );
  128. print('get请求成功!$url');
  129. } on DioError catch (e) {
  130. if (CancelToken.isCancel(e)) {
  131. print('get请求取消! ' + e.message);
  132. }
  133. print('get请求发生错误:$e');
  134. }
  135. return response;
  136. }
  137. Future post(url,
  138. {data,
  139. options,
  140. cancelToken,
  141. bool isShowLoading = false,
  142. failback}) async {
  143. print('post请求启动! url:$url ,body: $data');
  144. Response response;
  145. if (isShowLoading) LoadingManage().showLoading();
  146. try {
  147. response = await dio.post(
  148. url,
  149. data: data,
  150. cancelToken: cancelToken,
  151. );
  152. print('$url post请求成功! $BaseUrl');
  153. if (isShowLoading) LoadingManage().closeLoading();
  154. } on DioError catch (e) {
  155. if (CancelToken.isCancel(e)) {
  156. print('post请求取消! ' + e.message);
  157. }
  158. print('post请求发生错误:$e');
  159. if (isShowLoading) LoadingManage().closeLoading();
  160. showToast(I18n.of(Constants.getCurrentContext()).server_error_tips);
  161. if (failback != null) failback();
  162. }
  163. return response;
  164. }
  165. // 上传文件
  166. Future uploadFile(File imgfile, data, url, contentType,
  167. {isShowLoading = false}) async {
  168. FormData formData = new FormData.fromMap({
  169. "type": data["type"],
  170. "userId": data["userId"],
  171. "sex": data['sex'] == null ? 0 : data['sex'],
  172. "isBurn": data['isBurn'] == null ? 0 : data['isBurn'],
  173. "sign": data['sign'],
  174. "file": await getMultipartFile(imgfile, contentType)
  175. });
  176. print('post请求启动! url:$url');
  177. if (isShowLoading) LoadingManage().showLoading();
  178. Response response;
  179. try {
  180. response = await dio.post(
  181. url,
  182. data: formData,
  183. );
  184. print('post请求成功!response.data:${response.data}');
  185. if (isShowLoading) LoadingManage().closeLoading();
  186. } on DioError catch (e) {
  187. if (CancelToken.isCancel(e)) {
  188. print('post请求取消! ' + e.message);
  189. }
  190. print('post请求发生错误:$e');
  191. if (isShowLoading) LoadingManage().closeLoading();
  192. }
  193. return response;
  194. }
  195. Future<MultipartFile> getMultipartFile(
  196. File imgfile, String contentType) async {
  197. //压缩图片文件
  198. var size = await imgfile.length();
  199. String path = imgfile.path;
  200. var fileBytes;
  201. if (contentType == 'image' && size > 10240) {
  202. fileBytes = await WidgetUtil.getCompressImg(path,quality: 80,percentage: 80);
  203. } else {
  204. fileBytes = imgfile.readAsBytesSync();
  205. }
  206. var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  207. var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
  208. return new MultipartFile.fromBytes(fileBytes,
  209. filename: name, contentType: MediaType(contentType, suffix));
  210. }
  211. // 上传多个图片
  212. Future uploadFiles(List<File> imgfileList, data, url, contentType,
  213. {isShowLoading = false}) async {
  214. var imgList = [];
  215. for (int i = 0; i < imgfileList.length; i++) {
  216. imgList.add(await getMultipartFile(imgfileList[i], contentType));
  217. }
  218. FormData formData = new FormData.fromMap({
  219. "type": data["type"],
  220. "userId": data["userId"],
  221. "sex": data['sex'] == null ? 0 : data['sex'],
  222. "isBurn": data['isBurn'] == null ? 0 : data['isBurn'],
  223. "sign": data['sign'],
  224. "file": imgList
  225. });
  226. print('post请求启动! url:$url');
  227. if (isShowLoading) LoadingManage().showLoading();
  228. Response response;
  229. try {
  230. response = await dio.post(
  231. url,
  232. data: formData,
  233. );
  234. print('post请求成功!response.data:${response.data}');
  235. if (isShowLoading) LoadingManage().closeLoading();
  236. } on DioError catch (e) {
  237. if (CancelToken.isCancel(e)) {
  238. print('post请求取消! ' + e.message);
  239. }
  240. print('post请求发生错误:$e');
  241. if (isShowLoading) LoadingManage().closeLoading();
  242. }
  243. return response;
  244. }
  245. Future getUserInfoFromServer(int friendId) async {
  246. Map<String, dynamic> data = {
  247. "visitUserId": UserData().basicInfo.userId,
  248. "userId": friendId,
  249. "language": UserData().language,
  250. };
  251. data['sign'] = TokenMgr().getSign(data);
  252. data['lat'] = UserData().latitude;
  253. data['lng'] = UserData().longitude;
  254. print('请求用户信息 $data}');
  255. print('从服务器获取用户信息$friendId');
  256. Response res = await HttpUtil().post('user/info/list', data: data);
  257. if (res == null) {
  258. return null;
  259. }
  260. Map resData = res.data;
  261. print('用户信息resData $resData');
  262. if (resData['code'] == 0) {
  263. var info = UserInfo.fromJson(resData['data']);
  264. info.isBlackened
  265. ? BlacklistMgr.addBlackListMe(info.userId)
  266. : BlacklistMgr.removeBalckListMe(info.userId);
  267. info.isBlackList
  268. ? BlacklistMgr.addMyBlackList(info.userId)
  269. : BlacklistMgr.removeMyBalckList(info.userId);
  270. friendCache[friendId] = info;
  271. FriendListMgr().updateFriendInfo(info);
  272. UserInfoTable().insertUser(info);
  273. MessageMgr().emit('UpdateUserInfo', info);
  274. return info;
  275. } else {
  276. return null;
  277. }
  278. }
  279. Future getFriendInfo(int friendId, [bool isUpdate = false]) async {
  280. print('开始获取用户信息$friendId');
  281. if (friendId == null) {
  282. print('用户Id为空,无法获取信息');
  283. return null;
  284. }
  285. if (friendCache[friendId] != null) {
  286. print('存在用户信息$friendId 缓存');
  287. if (isUpdate) {
  288. //如果需要更新,那么先读取旧数据,然后后台更新
  289. getUserInfoFromServer(friendId);
  290. }
  291. return friendCache[friendId];
  292. }
  293. var info = await SqlUtil.userInfoTable.getUserInfoFromLocal(friendId);
  294. print('从本地数据库读取用户$friendId 信息');
  295. if (info != null) {
  296. if (isUpdate) {
  297. //如果需要更新,那么先读取旧数据,然后后台更新
  298. getUserInfoFromServer(friendId);
  299. }
  300. friendCache[friendId] = info;
  301. return info;
  302. }
  303. return await getUserInfoFromServer(friendId);
  304. }
  305. getUserInfo(visitedUserId, [callback, failcallback, errorcallback]) async {
  306. var data = {
  307. "visitUserId": UserData().basicInfo.userId,
  308. "userId": visitedUserId,
  309. "language": UserData().language,
  310. };
  311. data['sign'] = TokenMgr().getSign(data);
  312. data['lat'] = UserData().latitude;
  313. data['lng'] = UserData().longitude;
  314. Response res = await HttpUtil()
  315. .post('user/info/list', data: data, failback: errorcallback);
  316. if (res == null) {
  317. print('请求异常');
  318. return;
  319. }
  320. Map resData = res.data;
  321. if (resData['code'] == 0) {
  322. var info = UserInfo.fromJson(resData['data']);
  323. info.isBlackened
  324. ? BlacklistMgr.addBlackListMe(info.userId)
  325. : BlacklistMgr.removeBalckListMe(info.userId);
  326. info.isBlackList
  327. ? BlacklistMgr.addMyBlackList(info.userId)
  328. : BlacklistMgr.removeMyBalckList(info.userId);
  329. FriendListMgr().updateFriendInfo(info);
  330. friendCache[info.userId] = info;
  331. MessageMgr().emit('UpdateUserInfo', info);
  332. if (callback != null) callback(resData['data']);
  333. } else if (resData['code'] == -4) {
  334. if (failcallback != null) failcallback();
  335. }
  336. }
  337. getFirstProgram() async {
  338. Map data = {
  339. "userId": UserData().basicInfo.userId,
  340. "visitUserId": UserData().basicInfo.userId,
  341. "type": 1,
  342. };
  343. data['sign'] = TokenMgr().getSign(data);
  344. data['page'] = 1;
  345. data['rows'] = 1;
  346. Response res = await HttpUtil().post('station/gain/program', data: data);
  347. if (res == null) {
  348. print('请求异常');
  349. return;
  350. }
  351. var resData = res.data;
  352. if (resData['code'] == 0) {
  353. UserData().isCanProgram =
  354. resData['data'] == null || resData['data'][0]['Status'] == 1;
  355. }
  356. }
  357. Future getTranslateState(int sessionId) async {
  358. Map data = {
  359. "userId": UserData().basicInfo.userId,
  360. "chatUserId": sessionId,
  361. };
  362. data['sign'] = TokenMgr().getSign(data);
  363. Response res =
  364. await HttpUtil().post('translate/get/user/status', data: data);
  365. if (res == null) {
  366. print('请求异常');
  367. return null;
  368. }
  369. var resData = res.data;
  370. if (resData['code'] == 0) {
  371. return resData['data'];
  372. }
  373. return null;
  374. }
  375. updateTranslateState(int sessionId, bool state) async {
  376. Map data = {
  377. "userId": UserData().basicInfo.userId,
  378. "chatUserId": sessionId,
  379. "status": state ? 1 : 0
  380. };
  381. data['sign'] = TokenMgr().getSign(data);
  382. Response res = await HttpUtil().post('translate/set/up/status', data: data);
  383. if (res == null) {
  384. print('请求异常');
  385. return false;
  386. }
  387. var resData = res.data;
  388. if (resData['code'] == 0) {
  389. return true;
  390. }
  391. return false;
  392. }
  393. changeLanguage(BuildContext context, lang, callback,
  394. [showLoading = false]) async {
  395. var data = {
  396. "userid": UserData().basicInfo.userId,
  397. "language": lang,
  398. };
  399. data['sign'] = TokenMgr().getSign(data);
  400. try {
  401. Response res = await HttpUtil().post('user/setting/language',
  402. data: data, isShowLoading: showLoading);
  403. if (res == null) {
  404. print('请求异常');
  405. return;
  406. }
  407. Map resData = res.data;
  408. if (resData['code'] == 0) {
  409. if (callback != null) callback();
  410. //重新登录
  411. // SocketUtil().reLogin();
  412. NetWork().reLogin();
  413. }
  414. } catch (e) {}
  415. }
  416. userFreeTime(BuildContext context, var viewUserId, int type, callback) async {
  417. Map data = {
  418. "userId": UserData().basicInfo.userId,
  419. "viewUserId": viewUserId,
  420. 'type': type,
  421. };
  422. data['sign'] = TokenMgr().getSign(data);
  423. try {
  424. Response res = await HttpUtil()
  425. .post('photos/unlock/permissions', data: data, isShowLoading: true);
  426. if (res == null) {
  427. print('请求异常');
  428. return;
  429. }
  430. Map resData = res.data;
  431. if (resData['code'] == 0) {
  432. if (callback != null) callback();
  433. }
  434. } catch (e) {}
  435. }
  436. saveAotuLoginKey(resData, {bool isSaveUserId = true}) async {
  437. //将用户信息存到本地
  438. if (resData['data']['aotuLoginKey'] != null) {
  439. SharedPreferences prefs = await SharedPreferences.getInstance();
  440. await prefs.setString(
  441. Constants.AutoLoginKey, resData['data']['aotuLoginKey']);
  442. if (isSaveUserId) {
  443. await prefs.setInt(Constants.LocalUserId, UserData().basicInfo.userId);
  444. }
  445. }
  446. }
  447. ///登录
  448. changePage(BuildContext context, Map resData) async {
  449. UserData().basicInfo.userId = resData['data']['userid'];
  450. UserData().basicInfo.sex = resData['data']['sex'];
  451. if (resData['data']['mobile'] != null && resData['data']['mobile'] != '') {
  452. UserData().mobile = int.parse(resData['data']['mobile']);
  453. }
  454. if (resData['data']['bindId'] != null) {
  455. UserData().agentId = resData['data']['bindId'];
  456. }
  457. //读取聊天信息
  458. await ChatDataMgr().initMsg();
  459. //读取群信息
  460. await GroupInfoMgr().initLocalGroupList();
  461. print('~~~~~~~~~~~~~changePage~~~~~~~~~~~~~~~~~~~~~~');
  462. changeLanguage(context, UserData().language, null);
  463. getRewardAndRedPacketState();
  464. //clearReadData(UserData().basicInfo.userId);
  465. if (resData['data']['sex'] == 0) {
  466. Navigator.of(context).push(
  467. new MaterialPageRoute(
  468. builder: (context) {
  469. return SelectSex();
  470. },
  471. ),
  472. );
  473. saveAotuLoginKey(resData, isSaveUserId: false);
  474. return;
  475. }
  476. if (resData['data']['info'] == 0) {
  477. Navigator.of(context).push(
  478. new MaterialPageRoute(
  479. builder: (context) {
  480. return EditPage(
  481. isEditPage: false,
  482. );
  483. },
  484. ),
  485. );
  486. saveAotuLoginKey(resData, isSaveUserId: false);
  487. return;
  488. }
  489. LocalNotificationUtil.instance.startPush();
  490. //ChatDataMgr().initMsg();
  491. Navigator.of(context)
  492. .pushNamedAndRemoveUntil('/main', (route) => route == null);
  493. MessageMgr().emit('update_system');
  494. saveAotuLoginKey(resData);
  495. getFirstProgram();
  496. initLocation();
  497. }
  498. initLocation() async {
  499. SharedPreferences prefs = await SharedPreferences.getInstance();
  500. var latitude = prefs.getDouble(Constants.Latitude);
  501. var longitude = prefs.getDouble(Constants.Longitude);
  502. print('存贮在本地的位置: $latitude------$longitude');
  503. if (latitude != null) UserData().latitude = latitude;
  504. if (longitude != null) UserData().longitude = longitude;
  505. }
  506. setPhote(BuildContext context, id, type, callback) async {
  507. var data = {
  508. "userId": UserData().basicInfo.userId,
  509. "type": type,
  510. "pId": id,
  511. };
  512. data['sign'] = TokenMgr().getSign(data);
  513. Response res = await HttpUtil()
  514. .post('photos/setting/burns', data: data, isShowLoading: true);
  515. if (res == null) {
  516. print('请求异常');
  517. return;
  518. }
  519. var resData = res.data;
  520. showToast(resData['msg']);
  521. if (resData['code'] == 0) {
  522. if (callback != null) callback();
  523. }
  524. }
  525. clearCacheData() async {
  526. print('######### 清除缓存key');
  527. SharedPreferences prefs = await SharedPreferences.getInstance();
  528. prefs.remove(Constants.AutoLoginKey);
  529. prefs.remove(Constants.LocalUserId);
  530. prefs.remove(Constants.LocalUsrInfo);
  531. }
  532. // clearReadData(userId) async {
  533. // SharedPreferences prefs = await SharedPreferences.getInstance();
  534. // var localUserId = prefs.getInt(Constants.LocalUserId);
  535. // if (userId != localUserId) {
  536. // prefs.remove(Constants.ApplyCount);
  537. // prefs.remove(Constants.EvaluateCount);
  538. // prefs.remove(Constants.ParkCount);
  539. // prefs.remove(Constants.CastCount);
  540. // prefs.remove(Constants.WalletCount);
  541. // }
  542. // }
  543. void postLoginOut(BuildContext context) async {
  544. Map data = {
  545. "userId": UserData().basicInfo.userId,
  546. };
  547. data['sign'] = TokenMgr().getSign(data);
  548. Response res = await HttpUtil().post('user/login/out', data: data);
  549. if (res == null) {
  550. print('请求异常');
  551. return;
  552. }
  553. Map resData = res.data;
  554. if (resData['code'] == 0) {
  555. clearCacheData();
  556. FriendListMgr().friendList?.clear();
  557. Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(
  558. builder: (context) {
  559. return IndexPage();
  560. },
  561. ), (route) => route == null);
  562. NetWork().singOut();
  563. UserData().reset();
  564. } else {
  565. showToast(resData['msg']);
  566. }
  567. }
  568. buyGoods(money, goodsId, detailtype, changeuserId, context, callback) async {
  569. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  570. showToast(I18n.of(context).balance_insufficien);
  571. return;
  572. }
  573. var data = {
  574. "userId": UserData().basicInfo.userId,
  575. "type": 1,
  576. "detailtype": detailtype,
  577. };
  578. data['sign'] = TokenMgr().getSign(data);
  579. data['value'] = money;
  580. data['changeuserId'] = changeuserId;
  581. data['membergoodsId'] = goodsId;
  582. Response res = await HttpUtil()
  583. .post('wealth/user/add', data: data, isShowLoading: true);
  584. if (res == null) {
  585. print('请求异常');
  586. return;
  587. }
  588. Map resData = res.data;
  589. showToast(resData['msg']);
  590. if (resData['code'] == 0) {
  591. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  592. if (callback != null) callback();
  593. }
  594. }
  595. buyPictures(money, changeuserId, context, callback) async {
  596. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  597. showToast(I18n.of(context).balance_insufficien);
  598. return;
  599. }
  600. var data = {
  601. "userId": UserData().basicInfo.userId,
  602. "viewUserId": changeuserId,
  603. "price": money,
  604. };
  605. data['sign'] = TokenMgr().getSign(data);
  606. Response res = await HttpUtil()
  607. .post('photos/user/unlock', data: data, isShowLoading: true);
  608. if (res == null) {
  609. print('请求异常');
  610. return;
  611. }
  612. Map resData = res.data;
  613. showToast(resData['msg']);
  614. if (resData['code'] == 0) {
  615. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  616. if (callback != null) callback();
  617. }
  618. }
  619. buyVIP(int money, int gid, int type, BuildContext context, callback) async {
  620. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  621. showToast(I18n.of(context).balance_insufficien);
  622. return;
  623. }
  624. Map data = {
  625. "userId": UserData().basicInfo.userId,
  626. "gid": gid,
  627. "type": type,
  628. "price": money,
  629. };
  630. data['sign'] = TokenMgr().getSign(data);
  631. Response res = await HttpUtil()
  632. .post('goods/user/purchase', data: data, isShowLoading: true);
  633. if (res == null) {
  634. print('请求异常');
  635. return;
  636. }
  637. Map resData = res.data;
  638. showToast(resData['msg']);
  639. if (resData['code'] == 0) {
  640. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  641. if (callback != null) callback();
  642. }
  643. }
  644. buyChatAccount(money, changeuserId, context, callback) async {
  645. if (Provider.of<MoneyChangeProvider>(context).money < money) {
  646. showToast(I18n.of(context).balance_insufficien);
  647. return;
  648. }
  649. var data = {
  650. "userId": UserData().basicInfo.userId,
  651. "unlockUserId": changeuserId,
  652. "price": money,
  653. };
  654. data['sign'] = TokenMgr().getSign(data);
  655. Response res = await HttpUtil()
  656. .post('photos/pay/unlock/chat', data: data, isShowLoading: true);
  657. if (res == null) {
  658. print('请求异常');
  659. return;
  660. }
  661. Map resData = res.data;
  662. showToast(resData['msg']);
  663. if (resData['code'] == 0) {
  664. Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(money);
  665. if (callback != null) callback();
  666. }
  667. }
  668. void getMoneyInfo(BuildContext context, callback) async {
  669. if (Platform.isIOS) {
  670. await MoneyPageState.initPayConf(context);
  671. }
  672. Map data = {
  673. "userid": UserData().basicInfo.userId,
  674. "moneytype":
  675. UserData().language == LanguageType.SimplifiedChinese ? 0 : 1,
  676. "mobiletype": Platform.isIOS ? 0 : 1,
  677. };
  678. if (Platform.isIOS) {
  679. data['moneytype'] = 1;
  680. }
  681. print('moneytype ${data['moneytype']}');
  682. data['sign'] = TokenMgr().getSign(data);
  683. Response res = await HttpUtil()
  684. .post('goods/info/list', data: data, isShowLoading: true);
  685. if (res == null) {
  686. print('请求异常');
  687. return;
  688. }
  689. Map resData = res.data;
  690. if (resData['code'] == 0) {
  691. if (callback != null) callback(resData['data']);
  692. }
  693. }
  694. void getWealth(BuildContext context, callback) async {
  695. Map data = {
  696. "userId": UserData().basicInfo.userId,
  697. };
  698. data['sign'] = TokenMgr().getSign(data);
  699. Response res = await HttpUtil().post('wealth/user/info', data: data);
  700. if (res == null) {
  701. print('请求异常');
  702. return;
  703. }
  704. Map resData = res.data;
  705. print(resData);
  706. if (resData['code'] == 0 && resData['data'] != null) {
  707. UserData().basicInfo.isMember = resData['data']['IsMember'] ?? 0;
  708. UserData().incomeMoney = resData['data']['IncomeCoin'];
  709. UserData().frozenMoney = resData['data']['FrozenCoin'];
  710. UserData().memberEndTime = resData['data']['MemberEnd'];
  711. if (callback != null) callback(resData['data']);
  712. }
  713. }
  714. //获取红包与打赏开关状态
  715. getRewardAndRedPacketState() async {
  716. var myId = UserData().basicInfo.userId;
  717. Map data = {
  718. "userId": myId,
  719. };
  720. data['sign'] = TokenMgr().getSign(data);
  721. Response res = await HttpUtil().post('system/switch', data: data);
  722. if (res == null) {
  723. print('请求异常');
  724. return;
  725. }
  726. Map resData = res.data;
  727. print('### system/switch' + resData.toString());
  728. if (resData['code'] == 0) {
  729. var config = resData['data'];
  730. if (config != null) {
  731. UserData().redPacketSW = config['redPacket'];
  732. UserData().giftSwitch = config['reward'];
  733. UserData().bannerZF = config['iapPay'];
  734. UserData().sign = config['sign'];
  735. UserData().groupQRCode = config['groupQRCode'];
  736. UserData().addFdDistanceSwitch = config['distance'] ?? 0;
  737. UserData().stationOpenSwitch = config['station'] == 1;
  738. UserData().myProgramOpenSwitch = config['myProgram'] == 1;
  739. UserData().nearbyOpenSwitch = config['nearby'] == 1;
  740. // print('### config: start');
  741. // print('### config: iapPay:${config['iapPay']}');
  742. }
  743. }
  744. }
  745. ///检查是否有缓存的内购单-有的话向服务器发送请求重新创建订单
  746. void checkReceiptCache() async {
  747. String str = await SPUtils.get(Constants.IOS_IAP_Receipt);
  748. if (str != null && str.isNotEmpty) {
  749. print('### 有缓存单');
  750. List<String> split = str.split("@");
  751. createOrder(split[0], split[1], split[2]);
  752. } else {
  753. print('### 没有缓存单');
  754. }
  755. }
  756. ///ios内购-创建订单
  757. void createOrder(String currentGoodsId, String receipt, String purchaseToken,
  758. {BuildContext context}) async {
  759. // String base84str = base64Encode(utf8.encode(receipt));
  760. var data = {
  761. "userid": UserData().basicInfo.userId,
  762. "moneytype": 1,
  763. 'gid': currentGoodsId,
  764. "payway": 1,
  765. };
  766. data['sign'] = TokenMgr().getSign(data);
  767. data['receipt'] = receipt;
  768. data['isenable'] = Constants.isSandbox ? 0 : 1;
  769. Response res = await HttpUtil().post('order/add/goods', data: data);
  770. print('#### 创建订单-返回');
  771. if (res == null) {
  772. print('请求异常');
  773. return;
  774. }
  775. Map resData = res.data;
  776. print('#### 创建订单-返回:' + resData.toString());
  777. if (resData['code'] == 0) {
  778. // String OrderNo = resData['data']['OrderNo'];
  779. Future.delayed(Duration(seconds: 3), () {
  780. MessageMgr().emit('refresh_money');
  781. });
  782. if (context == null) {
  783. await FlutterInappPurchase.instance.initConnection;
  784. }
  785. FlutterInappPurchase.instance.finishTransaction(purchaseToken);
  786. SPUtils.remove(Constants.IOS_IAP_Receipt);
  787. } else {
  788. ///创建订单失败-
  789. await SPUtils.saveString(Constants.IOS_IAP_Receipt,
  790. currentGoodsId + '@' + receipt + '@' + purchaseToken);
  791. }
  792. if (context != null) {
  793. Navigator.of(context).pop();
  794. }
  795. }
  796. ///登陆
  797. void login(
  798. String _phoneNumber, String _passWorld, BuildContext context) async {
  799. var data = {
  800. "mobile": _phoneNumber,
  801. "text": _passWorld,
  802. "type": 0,
  803. "language": UserData().language,
  804. };
  805. data['sign'] = TokenMgr().getSign(data);
  806. Response res = await HttpUtil()
  807. .post('user/mobile/login', data: data, isShowLoading: true);
  808. if (res == null) {
  809. print('请求异常');
  810. return;
  811. }
  812. var resData = res.data;
  813. if (resData['code'] == 0 && resData['data'] != null) {
  814. HttpUtil().changePage(context, resData);
  815. } else {
  816. showToast(resData['msg']);
  817. }
  818. }
  819. ///获取推送设置
  820. getSettingInfo() async {
  821. Map data = {
  822. "userId": UserData().basicInfo.userId,
  823. "sex": UserData().basicInfo.sex,
  824. };
  825. data['sign'] = TokenMgr().getSign(data);
  826. try {
  827. Response res = await HttpUtil().post('message/push/message', data: data);
  828. if (res == null) {
  829. print('请求异常');
  830. return;
  831. }
  832. Map resData = res.data;
  833. bool isMan = UserData().isMan();
  834. ///女号 {data: {PrivacyChat: 1, NewBroadcast: 1, ApplyCheck: 1, CheckAccount: 1, CheckPhoto: 1, SendAccount: 1}, code: 0, msg: 成功}
  835. ///男号 {data: {PrivacyChat: 1, NewBroadcast: 1, AcceptCheck: 1, ApplySuccess: 1}, code: 0, msg: 成功}
  836. print('###settingdata res.data ${res.data}');
  837. if (resData['code'] == 0) {
  838. UserData().privatyMsgPushSwitch = resData['data']['PrivacyChat'] == 1;
  839. UserData().newDateSwitch = resData['data']['NewBroadcast'] == 1;
  840. if (isMan) {
  841. UserData().acceptCheckSwitch = resData['data']['AcceptCheck'] == 1;
  842. UserData().codeSucessSwitch = resData['data']['ApplySuccess'] == 1;
  843. } else {
  844. UserData().applyCheckSwitch = resData['data']['ApplyCheck'] == 1;
  845. UserData().checkPhotoSwitch = resData['data']['CheckPhoto'] == 1;
  846. }
  847. }
  848. } catch (e) {}
  849. MessageMgr().emit(MessageMgr.REFRESH_PUSH_PERMISSION);
  850. }
  851. ///版本控制
  852. appVersionUpdate(Function callBack) async {
  853. Map data = {
  854. "ditch": Constants.isStoreVersion ? 0 : 1,
  855. "type": Platform.isAndroid ? 0 : 1,
  856. };
  857. data['sign'] = TokenMgr().getSign(data);
  858. data['language'] = UserData().language;
  859. try {
  860. Response res = await HttpUtil().post('system/version/info', data: data);
  861. Map resData = res.data;
  862. print('###appVersionUpdate res.data ${res.data}');
  863. if (resData['code'] == 0) {
  864. bool needNotice = resData['data']['Notice'] == 1;
  865. ///是否通知更新
  866. bool forceUpdate = resData['data']['IsStronger'] == 1;
  867. ///是否通知强更
  868. String version = resData['data']['VersionNo'];
  869. String describe = resData['data']['Describe'];
  870. String downloadUrl = resData['data']['DownloadUrl'];
  871. String appId = resData['data']['AppId'];
  872. callBack(
  873. needNotice, forceUpdate, version, describe, downloadUrl, appId);
  874. }
  875. } catch (e) {}
  876. }
  877. downloadApk(
  878. BuildContext context,
  879. String filePath,
  880. String downloadUrl,
  881. Function downloadCallback,
  882. ) async {
  883. final file = new File(filePath);
  884. bool isExist = await file.exists();
  885. if (isExist) {
  886. print('### 文件存在 : ${file.path}');
  887. file.delete();
  888. }
  889. // else {
  890. //
  891. // print('### 开始下载 $downloadUrl');
  892. // dio.download(downloadUrl, filePath, onReceiveProgress: downloadCallback);
  893. // }
  894. // downloadUrl ='oemarket.com/app0/30/30970/apk/2085562.apk?channel_id=426&tid=d73j9ihlkucuxfqpgnxgjeif';
  895. dio.download(downloadUrl, filePath, onReceiveProgress: downloadCallback);
  896. }
  897. ///获取用户每日签到信息
  898. Future<DailyBonusBean> getDailyBonus() async {
  899. Map data = {
  900. "userId": UserData().basicInfo.userId,
  901. };
  902. data['sign'] = TokenMgr().getSign(data);
  903. data['userId'] = UserData().basicInfo.userId;
  904. try {
  905. Response res = await HttpUtil().post('sign/in/user/info', data: data);
  906. Map resData = res.data;
  907. print('###getDailyBonus res.data ${res.data}');
  908. if (resData['code'] == 0) {
  909. return DailyBonusBean.fromMap(resData['data']);
  910. }
  911. return null;
  912. } catch (e) {
  913. return null;
  914. }
  915. }
  916. ///点击签到
  917. Future<bool> signInBounus(int score) async {
  918. Map data = {
  919. "userId": UserData().basicInfo.userId,
  920. "score": score,
  921. };
  922. data['sign'] = TokenMgr().getSign(data);
  923. data['userId'] = UserData().basicInfo.userId;
  924. data['score'] = score;
  925. try {
  926. Response res = await HttpUtil().post('sign/in/user', data: data);
  927. Map resData = res.data;
  928. print('###signInBounus res.data ${res.data}');
  929. if (resData['code'] == 0) {
  930. return true;
  931. // bool needNotice = resData['data']['Notice']==1; ///是否通知更新
  932. // return DailyBonusBean.fromMap(resData['data']);
  933. } else {
  934. showToast(resData['msg']);
  935. }
  936. return false;
  937. } catch (e) {
  938. return false;
  939. }
  940. }
  941. /// 用户签到积分兑换商品
  942. Future<bool> signInExchange(GoodsBean goodsBean) async {
  943. Map data = {
  944. "userId": UserData().basicInfo.userId,
  945. "id": goodsBean.id,
  946. "score": goodsBean.s,
  947. };
  948. data['sign'] = TokenMgr().getSign(data);
  949. data['userId'] = UserData().basicInfo.userId;
  950. data['score'] = goodsBean.s;
  951. data['id'] = goodsBean.id;
  952. try {
  953. Response res =
  954. await HttpUtil().post('sign/in/score/exchange', data: data);
  955. Map resData = res.data;
  956. print('###signInExchange res.data ${res.data}');
  957. if (resData['code'] == 0) {
  958. return true;
  959. } else {
  960. showToast(resData['msg']);
  961. }
  962. return false;
  963. } catch (e) {
  964. return false;
  965. }
  966. }
  967. addFriends(
  968. BuildContext context, int friendId, String content, callback) async {
  969. Map data = {
  970. "userId": UserData().basicInfo.userId,
  971. "friendsUserId": friendId
  972. };
  973. data['sign'] = TokenMgr().getSign(data);
  974. data['content'] = content;
  975. Response res = await HttpUtil().post('friendship/add/friends', data: data);
  976. Map resData = res.data;
  977. print(resData);
  978. if (resData['code'] == 0) {
  979. showToast(resData['msg']);
  980. if (callback != null) callback();
  981. }
  982. }
  983. //付费人工翻译
  984. getPersonalTranslate(MsgModel msgModel) async {
  985. Map data = {
  986. "suserid": msgModel.from,
  987. "chatmsgid": msgModel.time,
  988. "slanguage": 1,
  989. "tlanguage": UserData().language,
  990. "chattype": msgModel.msgType,
  991. "chatchanneltype": msgModel.channelType,
  992. "targetid": msgModel.sessionId
  993. };
  994. data['sign'] = TokenMgr().getSign(data);
  995. if (msgModel.msgType == 0) {
  996. data['content'] = base64Encode(msgModel.msgContent);
  997. } else {
  998. if (msgModel.localFile == null) {
  999. showToast('请稍后再试');
  1000. return;
  1001. }
  1002. data['content'] =
  1003. base64Encode(File(msgModel.localFile).readAsBytesSync());
  1004. }
  1005. data["tuserids"] = [UserData().basicInfo.userId];
  1006. data['duration'] =
  1007. msgModel.extraInfo != null ? msgModel.extraInfo ~/ 1000 : 0;
  1008. data['ispay'] = true;
  1009. if (msgModel.msgType == ChatType.TextChatType.value) {
  1010. int length = utf8.decode(msgModel.msgContent).length;
  1011. data['money'] = length ~/ 50 + 1; //每50个字耗费1H币
  1012. print('字数 $length 价格 ${length % 50 + 1}');
  1013. } else if (msgModel.msgType == ChatType.ShortVoiceChatType.value) {
  1014. //没20秒扣除1Hb
  1015. data['money'] =
  1016. msgModel.extraInfo != null ? msgModel.extraInfo ~/ 20000 + 1 : 0;
  1017. }
  1018. if (msgModel.translateContent != null &&
  1019. msgModel.translateContent.length > 0) {
  1020. data['mcontent'] = base64Encode(msgModel.enTranslateContent);
  1021. }
  1022. Response res =
  1023. await HttpUtil().post('service/paid/translation', data: data);
  1024. if (res == null) {
  1025. return false;
  1026. }
  1027. Map resData = res.data;
  1028. print('付费翻译请求$resData');
  1029. if (resData['code'] == 0) {
  1030. print('扣除 H 币 ${data['money']}');
  1031. return true;
  1032. }
  1033. print(resData['msg']);
  1034. showToast(resData['msg']);
  1035. return false;
  1036. }
  1037. //用户评价人工翻译,差评
  1038. Future<bool> rateTranslateResult(MsgModel msg, Function callback) async {
  1039. Map data = {
  1040. "userId": UserData().basicInfo.userId,
  1041. "chatUserId": msg.from,
  1042. "chatMsgId": msg.time,
  1043. "score": 1
  1044. };
  1045. data['sign'] = TokenMgr().getSign(data);
  1046. Response res = await HttpUtil().post('translate/user/score', data: data);
  1047. if (res == null) {
  1048. return false;
  1049. }
  1050. var resData = res.data;
  1051. if (resData['code'] == 0) {
  1052. msg.transTag = 10; //已评价过
  1053. if (callback != null) {
  1054. callback();
  1055. }
  1056. SqlUtil().updateUserTranslateRate(msg.sessionId, msg.time, msg.transTag);
  1057. return true;
  1058. }
  1059. return false;
  1060. }
  1061. //根据经纬度获取用户国家城市
  1062. getAddress(double lon, double lat) async {
  1063. Map data = {
  1064. "lon": lon.toString(),
  1065. "lat": lat.toString(),
  1066. };
  1067. data['sign'] = TokenMgr().getSign(data);
  1068. data['language'] = UserData().language;
  1069. Response res = await HttpUtil().post('user/get/address', data: data);
  1070. if (res == null) return;
  1071. Map resData = res.data;
  1072. if (resData['code'] == 0 && resData['data'] != null) {
  1073. print(resData['data']);
  1074. List address = resData['data'].split(',');
  1075. if (address.length != 2) return;
  1076. String country = address[0];
  1077. String city = address[1];
  1078. UserData().isInChina = false;
  1079. if (country == '越南') {
  1080. UserData().currentCity = 'VietNam-';
  1081. List citys = constData[3]['city'][0]['List'];
  1082. for (int i = 0; i < citys.length; i++) {
  1083. if (citys[i]['Value'] == city) {
  1084. UserData().currentCity += citys[i]['Key'];
  1085. break;
  1086. }
  1087. }
  1088. } else if (country == '中国') {
  1089. UserData().isInChina = true;
  1090. UserData().currentCity = 'China-ChinaRepeat';
  1091. } else {
  1092. UserData().currentCity = 'VietNam-HoChiMinhCIty';
  1093. }
  1094. if (UserData().currentCity != UserData().basicInfo.meetPlace) {
  1095. UserData().basicInfo.meetPlace = UserData().currentCity;
  1096. changeCurrentCity(lon, lat, () {});
  1097. }
  1098. MessageMgr().emit('change_currentcity');
  1099. }
  1100. }
  1101. //根据经纬度获取用户国家城市
  1102. changeCurrentCity(double lon, double lat, callback) async {
  1103. if (UserData().basicInfo.userId == null) return;
  1104. Map data = {
  1105. "userId": UserData().basicInfo.userId,
  1106. "lon": lon.toString(),
  1107. "lat": lat.toString(),
  1108. };
  1109. data['sign'] = TokenMgr().getSign(data);
  1110. Response res = await HttpUtil().post('user/update/meetPlace', data: data);
  1111. if (res == null) return;
  1112. Map resData = res.data;
  1113. print(resData);
  1114. if (resData['code'] == 0) {
  1115. callback();
  1116. }
  1117. }
  1118. //通过手机号查询用户
  1119. searchNewFrindsByPhone(String phone, callback) async {
  1120. Map data = {
  1121. "userId": UserData().basicInfo.userId,
  1122. "value": phone,
  1123. };
  1124. data['sign'] = TokenMgr().getSign(data);
  1125. Response res = await HttpUtil()
  1126. .post('/friendship/search/userPhone', data: data, isShowLoading: true);
  1127. if (res == null) return;
  1128. Map resData = res.data;
  1129. print(resData);
  1130. if (resData['code'] == 0) {
  1131. callback(resData['data']['UserId']);
  1132. }
  1133. }
  1134. //拉黑用户
  1135. blackUser(int userId, callback) async {
  1136. Map data = {
  1137. "userid": UserData().basicInfo.userId,
  1138. "type": 1,
  1139. "followUserId": userId,
  1140. };
  1141. data['sign'] = TokenMgr().getSign(data);
  1142. Response res =
  1143. await HttpUtil().post('userfollow/follow/insert', data: data);
  1144. Map resData = res.data;
  1145. showToast(resData['msg']);
  1146. if (resData['code'] == 0) {
  1147. BlacklistMgr.addMyBlackList(userId);
  1148. callback();
  1149. }
  1150. }
  1151. //取消拉黑用户
  1152. cancleBlackUser(int userId, callback) async {
  1153. Map data = {
  1154. "userid": UserData().basicInfo.userId,
  1155. "type": 1,
  1156. "followUserId": userId,
  1157. };
  1158. data['sign'] = TokenMgr().getSign(data);
  1159. Response res = await HttpUtil()
  1160. .post('userfollow/follow/cancel', data: data, isShowLoading: true);
  1161. Map resData = res.data;
  1162. showToast(resData['msg']);
  1163. if (resData['code'] == 0) {
  1164. BlacklistMgr.removeMyBalckList(userId);
  1165. callback();
  1166. }
  1167. }
  1168. //收藏用户
  1169. setLove(int userId, callback) async {
  1170. Map data = {
  1171. "userid": UserData().basicInfo.userId,
  1172. "type": 0,
  1173. "followUserId": userId,
  1174. };
  1175. data['sign'] = TokenMgr().getSign(data);
  1176. Response res = await HttpUtil()
  1177. .post('userfollow/follow/insert', data: data, isShowLoading: true);
  1178. Map resData = res.data;
  1179. if (resData['code'] == 0) {
  1180. showToast(resData['msg']);
  1181. callback();
  1182. }
  1183. }
  1184. //取消收藏用户
  1185. cancleLove(int userId, callback) async {
  1186. Map data = {
  1187. "userid": UserData().basicInfo.userId,
  1188. "type": 0,
  1189. "followUserId": userId,
  1190. };
  1191. data['sign'] = TokenMgr().getSign(data);
  1192. Response res = await HttpUtil()
  1193. .post('userfollow/follow/cancel', data: data, isShowLoading: true);
  1194. Map resData = res.data;
  1195. if (resData['code'] == 0) {
  1196. showToast(resData['msg']);
  1197. callback();
  1198. }
  1199. }
  1200. //向企业服务助手提交信息
  1201. Future<bool> commitInfoToCompany(MsgModel msgModel) async {
  1202. Map data = {
  1203. "userid": msgModel.from,
  1204. "msgType": msgModel.msgType,
  1205. };
  1206. data['sign'] = TokenMgr().getSign(data);
  1207. data['msgContent'] = base64Encode(msgModel.msgContent);
  1208. msgModel.state = MsgState.Sending;
  1209. print('commitInfoToCompany 参数 $data');
  1210. Response res = await HttpUtil().post('feedback/user/insert', data: data);
  1211. if (res == null) {
  1212. msgModel.state = MsgState.SendingFailed;
  1213. ChatDataMgr().updateMsgState(msgModel.sessionId, msgModel.time,
  1214. msgModel.channelType, msgModel.state);
  1215. return false;
  1216. }
  1217. Map resData = res.data;
  1218. print('commitInfoToCompany $resData');
  1219. if (resData['code'] == 0) {
  1220. msgModel.state = MsgState.SendingSuccess;
  1221. ChatDataMgr().updateMsgState(msgModel.sessionId, msgModel.time,
  1222. msgModel.channelType, msgModel.state);
  1223. return true;
  1224. }
  1225. showToast(resData['msg']);
  1226. return false;
  1227. }
  1228. //焚阅照片恢复
  1229. resetPhoto(callback) async {
  1230. Map data = {
  1231. "userId": UserData().basicInfo.userId,
  1232. };
  1233. data['sign'] = TokenMgr().getSign(data);
  1234. Response res = await HttpUtil()
  1235. .post('user/recover/photos', data: data, isShowLoading: true);
  1236. Map resData = res.data;
  1237. if (resData['code'] == 0) {
  1238. showToast(resData['msg']);
  1239. callback();
  1240. }
  1241. }
  1242. }