ab_model.dart 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter_hbb/common/hbbs/hbbs.dart';
  6. import 'package:flutter_hbb/common/widgets/peers_view.dart';
  7. import 'package:flutter_hbb/consts.dart';
  8. import 'package:flutter_hbb/models/model.dart';
  9. import 'package:flutter_hbb/models/peer_model.dart';
  10. import 'package:flutter_hbb/models/platform_model.dart';
  11. import 'package:get/get.dart';
  12. import 'package:bot_toast/bot_toast.dart';
  13. import '../utils/http_service.dart' as http;
  14. import '../common.dart';
  15. final syncAbOption = 'sync-ab-with-recent-sessions';
  16. bool shouldSyncAb() {
  17. return bind.mainGetLocalOption(key: syncAbOption) == 'Y';
  18. }
  19. final sortAbTagsOption = 'sync-ab-tags';
  20. bool shouldSortTags() {
  21. return bind.mainGetLocalOption(key: sortAbTagsOption) == 'Y';
  22. }
  23. final filterAbTagOption = 'filter-ab-by-intersection';
  24. bool filterAbTagByIntersection() {
  25. return bind.mainGetLocalOption(key: filterAbTagOption) == 'Y';
  26. }
  27. const _personalAddressBookName = "My address book";
  28. const _legacyAddressBookName = "Legacy address book";
  29. enum ForcePullAb {
  30. listAndCurrent,
  31. current,
  32. }
  33. class AbModel {
  34. final addressbooks = Map<String, BaseAb>.fromEntries([]).obs;
  35. final RxString _currentName = ''.obs;
  36. RxString get currentName => _currentName;
  37. final _dummyAb = DummyAb();
  38. BaseAb get current => addressbooks[_currentName.value] ?? _dummyAb;
  39. RxList<Peer> get currentAbPeers => current.peers;
  40. RxList<String> get currentAbTags => current.tags;
  41. RxList<String> get selectedTags => current.selectedTags;
  42. RxBool get currentAbLoading => current.abLoading;
  43. bool get currentAbEmpty => current.peers.isEmpty && current.tags.isEmpty;
  44. RxString get currentAbPullError => current.pullError;
  45. RxString get currentAbPushError => current.pushError;
  46. String? _personalAbGuid;
  47. RxBool legacyMode = false.obs;
  48. final sortTags = shouldSortTags().obs;
  49. final filterByIntersection = filterAbTagByIntersection().obs;
  50. var _syncAllFromRecent = true;
  51. var _syncFromRecentLock = false;
  52. var _timerCounter = 0;
  53. var _cacheLoadOnceFlag = false;
  54. var listInitialized = false;
  55. var _maxPeerOneAb = 0;
  56. late final Peers peersModel;
  57. WeakReference<FFI> parent;
  58. AbModel(this.parent) {
  59. addressbooks.clear();
  60. peersModel = Peers(
  61. name: PeersModelName.addressBook,
  62. getInitPeers: () => currentAbPeers,
  63. loadEvent: LoadEvent.addressBook);
  64. if (desktopType == DesktopType.main) {
  65. Timer.periodic(Duration(milliseconds: 500), (timer) async {
  66. if (_timerCounter++ % 6 == 0) {
  67. if (!gFFI.userModel.isLogin) return;
  68. if (!listInitialized) return;
  69. if (!current.initialized || !current.canWrite()) return;
  70. _syncFromRecent();
  71. }
  72. });
  73. }
  74. }
  75. reset() async {
  76. print("reset ab model");
  77. addressbooks.clear();
  78. _currentName.value = '';
  79. await bind.mainClearAb();
  80. listInitialized = false;
  81. }
  82. // #region ab
  83. /// Pulls the address book data from the server.
  84. ///
  85. /// If `force` is `ForcePullAb.listAndCurrent`, the function will pull the list of address books, current address book, and try initialize personal address book.
  86. /// If `force` is `ForcePullAb.current`, the function will only pull the current address book.
  87. /// If `quiet` is true, the function will not display any notifications or errors.
  88. var _pulling = false;
  89. Future<void> pullAb(
  90. {required ForcePullAb? force, required bool quiet}) async {
  91. if (_pulling) return;
  92. _pulling = true;
  93. try {
  94. await _pullAb(force: force, quiet: quiet);
  95. _refreshTab();
  96. } catch (_) {}
  97. _pulling = false;
  98. }
  99. Future<void> _pullAb(
  100. {required ForcePullAb? force, required bool quiet}) async {
  101. if (bind.isDisableAb()) return;
  102. if (!gFFI.userModel.isLogin) return;
  103. if (gFFI.userModel.networkError.isNotEmpty) return;
  104. if (force == null && listInitialized && current.initialized) return;
  105. debugPrint("pullAb, force: $force, quiet: $quiet");
  106. if (!listInitialized || force == ForcePullAb.listAndCurrent) {
  107. try {
  108. // Read personal guid every time to avoid upgrading the server without closing the main window
  109. _personalAbGuid = null;
  110. await _getPersonalAbGuid();
  111. // Determine legacy mode based on whether _personalAbGuid is null
  112. legacyMode.value = _personalAbGuid == null;
  113. if (!legacyMode.value && _maxPeerOneAb == 0) {
  114. await _getAbSettings();
  115. }
  116. if (_personalAbGuid != null) {
  117. debugPrint("pull ab list");
  118. List<AbProfile> abProfiles = List.empty(growable: true);
  119. abProfiles.add(AbProfile(_personalAbGuid!, _personalAddressBookName,
  120. gFFI.userModel.userName.value, null, ShareRule.read.value));
  121. // get all address book name
  122. await _getSharedAbProfiles(abProfiles);
  123. addressbooks.removeWhere((key, value) =>
  124. abProfiles.firstWhereOrNull((e) => e.name == key) == null);
  125. for (int i = 0; i < abProfiles.length; i++) {
  126. AbProfile p = abProfiles[i];
  127. if (addressbooks.containsKey(p.name)) {
  128. addressbooks[p.name]?.setSharedProfile(p);
  129. } else {
  130. addressbooks[p.name] = Ab(p, p.guid == _personalAbGuid);
  131. }
  132. }
  133. } else {
  134. // only legacy address book
  135. addressbooks
  136. .removeWhere((key, value) => key != _legacyAddressBookName);
  137. if (!addressbooks.containsKey(_legacyAddressBookName)) {
  138. addressbooks[_legacyAddressBookName] = LegacyAb();
  139. }
  140. }
  141. // set current address book name
  142. if (!listInitialized) {
  143. listInitialized = true;
  144. trySetCurrentToLast();
  145. }
  146. if (!addressbooks.containsKey(_currentName.value)) {
  147. setCurrentName(legacyMode.value
  148. ? _legacyAddressBookName
  149. : _personalAddressBookName);
  150. }
  151. // pull current address book
  152. await current.pullAb(quiet: quiet);
  153. // try initialize personal address book
  154. if (!current.isPersonal()) {
  155. final personalAb = addressbooks[_personalAddressBookName];
  156. if (personalAb != null && !personalAb.initialized) {
  157. await personalAb.pullAb(quiet: quiet);
  158. }
  159. }
  160. } catch (e) {
  161. debugPrint("pull ab list error: $e");
  162. }
  163. } else if (listInitialized &&
  164. (!current.initialized || force == ForcePullAb.current)) {
  165. try {
  166. await current.pullAb(quiet: quiet);
  167. } catch (e) {
  168. debugPrint("pull current Ab error: $e");
  169. }
  170. }
  171. if (listInitialized && current.initialized) {
  172. _saveCache();
  173. }
  174. }
  175. Future<bool> _getAbSettings() async {
  176. try {
  177. final api = "${await bind.mainGetApiServer()}/api/ab/settings";
  178. var headers = getHttpHeaders();
  179. headers['Content-Type'] = "application/json";
  180. final resp = await http.post(Uri.parse(api), headers: headers);
  181. if (resp.statusCode == 404) {
  182. debugPrint("HTTP 404, api server doesn't support shared address book");
  183. return false;
  184. }
  185. Map<String, dynamic> json =
  186. _jsonDecodeRespMap(utf8.decode(resp.bodyBytes), resp.statusCode);
  187. if (json.containsKey('error')) {
  188. throw json['error'];
  189. }
  190. if (resp.statusCode != 200) {
  191. throw 'HTTP ${resp.statusCode}';
  192. }
  193. _maxPeerOneAb = json['max_peer_one_ab'] ?? 0;
  194. return true;
  195. } catch (err) {
  196. debugPrint('get ab settings err: ${err.toString()}');
  197. }
  198. return false;
  199. }
  200. Future<bool> _getPersonalAbGuid() async {
  201. try {
  202. final api = "${await bind.mainGetApiServer()}/api/ab/personal";
  203. var headers = getHttpHeaders();
  204. headers['Content-Type'] = "application/json";
  205. final resp = await http.post(Uri.parse(api), headers: headers);
  206. if (resp.statusCode == 404) {
  207. debugPrint("HTTP 404, current api server is legacy mode");
  208. return false;
  209. }
  210. Map<String, dynamic> json =
  211. _jsonDecodeRespMap(utf8.decode(resp.bodyBytes), resp.statusCode);
  212. if (json.containsKey('error')) {
  213. throw json['error'];
  214. }
  215. if (resp.statusCode != 200) {
  216. throw 'HTTP ${resp.statusCode}';
  217. }
  218. _personalAbGuid = json['guid'];
  219. return true;
  220. } catch (err) {
  221. debugPrint('get personal ab err: ${err.toString()}');
  222. }
  223. return false;
  224. }
  225. Future<bool> _getSharedAbProfiles(List<AbProfile> profiles) async {
  226. final api = "${await bind.mainGetApiServer()}/api/ab/shared/profiles";
  227. try {
  228. var uri0 = Uri.parse(api);
  229. final pageSize = 100;
  230. var total = 0;
  231. int current = 0;
  232. do {
  233. current += 1;
  234. var uri = Uri(
  235. scheme: uri0.scheme,
  236. host: uri0.host,
  237. path: uri0.path,
  238. port: uri0.port,
  239. queryParameters: {
  240. 'current': current.toString(),
  241. 'pageSize': pageSize.toString(),
  242. });
  243. var headers = getHttpHeaders();
  244. headers['Content-Type'] = "application/json";
  245. final resp = await http.post(uri, headers: headers);
  246. Map<String, dynamic> json =
  247. _jsonDecodeRespMap(utf8.decode(resp.bodyBytes), resp.statusCode);
  248. if (json.containsKey('error')) {
  249. throw json['error'];
  250. }
  251. if (resp.statusCode != 200) {
  252. throw 'HTTP ${resp.statusCode}';
  253. }
  254. if (json.containsKey('total')) {
  255. if (total == 0) total = json['total'];
  256. if (json.containsKey('data')) {
  257. final data = json['data'];
  258. if (data is List) {
  259. for (final profile in data) {
  260. final u = AbProfile.fromJson(profile);
  261. int index = profiles.indexWhere((e) => e.name == u.name);
  262. if (index < 0) {
  263. profiles.add(u);
  264. } else {
  265. profiles[index] = u;
  266. }
  267. }
  268. }
  269. }
  270. }
  271. } while (current * pageSize < total);
  272. return true;
  273. } catch (err) {
  274. debugPrint('_getSharedAbProfiles err: ${err.toString()}');
  275. }
  276. return false;
  277. }
  278. // #endregion
  279. // #region rule
  280. List<String> addressBooksCanWrite() {
  281. List<String> list = [];
  282. addressbooks.forEach((key, value) async {
  283. if (value.canWrite()) {
  284. list.add(key);
  285. }
  286. });
  287. return list;
  288. }
  289. // #endregion
  290. // #region peer
  291. Future<String?> addIdToCurrent(
  292. String id, String alias, String password, List<dynamic> tags) async {
  293. if (currentAbPeers.where((element) => element.id == id).isNotEmpty) {
  294. return "$id already exists in address book $_currentName";
  295. }
  296. Map<String, dynamic> peer = {
  297. 'id': id,
  298. 'alias': alias,
  299. 'tags': tags,
  300. };
  301. // avoid set existing password to empty
  302. if (password.isNotEmpty) {
  303. peer['password'] = password;
  304. }
  305. final ret = await addPeersTo([peer], _currentName.value);
  306. _syncAllFromRecent = true;
  307. return ret;
  308. }
  309. // Use Map<String, dynamic> rather than Peer to distinguish between empty and null
  310. Future<String?> addPeersTo(
  311. List<Map<String, dynamic>> ps,
  312. String name,
  313. ) async {
  314. final ab = addressbooks[name];
  315. if (ab == null) {
  316. return 'no such addressbook: $name';
  317. }
  318. String? errMsg = await ab.addPeers(ps);
  319. await pullNonLegacyAfterChange(name: name);
  320. if (name == _currentName.value) {
  321. _refreshTab();
  322. }
  323. _syncAllFromRecent = true;
  324. _saveCache();
  325. return errMsg;
  326. }
  327. Future<bool> changeTagForPeers(List<String> ids, List<dynamic> tags) async {
  328. bool ret = await current.changeTagForPeers(ids, tags);
  329. await pullNonLegacyAfterChange();
  330. currentAbPeers.refresh();
  331. _saveCache();
  332. return ret;
  333. }
  334. Future<bool> changeAlias({required String id, required String alias}) async {
  335. bool res = await current.changeAlias(id: id, alias: alias);
  336. await pullNonLegacyAfterChange();
  337. currentAbPeers.refresh();
  338. _saveCache();
  339. return res;
  340. }
  341. Future<bool> changePersonalHashPassword(String id, String hash) async {
  342. var ret = false;
  343. final personalAb = addressbooks[_personalAddressBookName];
  344. if (personalAb != null) {
  345. ret = await personalAb.changePersonalHashPassword(id, hash);
  346. await personalAb.pullAb(quiet: true);
  347. } else {
  348. final legacyAb = addressbooks[_legacyAddressBookName];
  349. if (legacyAb != null) {
  350. ret = await legacyAb.changePersonalHashPassword(id, hash);
  351. }
  352. }
  353. _saveCache();
  354. return ret;
  355. }
  356. Future<bool> changeSharedPassword(
  357. String abName, String id, String password) async {
  358. final ab = addressbooks[abName];
  359. if (ab == null) return false;
  360. final ret = await ab.changeSharedPassword(id, password);
  361. await ab.pullAb(quiet: true);
  362. return ret;
  363. }
  364. Future<bool> deletePeers(List<String> ids) async {
  365. final ret = await current.deletePeers(ids);
  366. await pullNonLegacyAfterChange();
  367. currentAbPeers.refresh();
  368. _refreshTab();
  369. _saveCache();
  370. if (legacyMode.value && current.isPersonal()) {
  371. // non-legacy mode not add peers automatically
  372. Future.delayed(Duration(seconds: 2), () async {
  373. if (!shouldSyncAb()) return;
  374. var hasSynced = false;
  375. for (var id in ids) {
  376. if (await bind.mainPeerExists(id: id)) {
  377. hasSynced = true;
  378. break;
  379. }
  380. }
  381. if (hasSynced) {
  382. BotToast.showText(
  383. contentColor: Colors.lightBlue,
  384. text: translate('synced_peer_readded_tip'));
  385. _syncAllFromRecent = true;
  386. }
  387. });
  388. }
  389. return ret;
  390. }
  391. // #endregion
  392. // #region tags
  393. Future<bool> addTags(List<String> tagList) async {
  394. final ret = await current.addTags(tagList, {});
  395. await pullNonLegacyAfterChange();
  396. _saveCache();
  397. return ret;
  398. }
  399. Future<bool> renameTag(String oldTag, String newTag) async {
  400. final ret = await current.renameTag(oldTag, newTag);
  401. await pullNonLegacyAfterChange();
  402. selectedTags.value = selectedTags.map((e) {
  403. if (e == oldTag) {
  404. return newTag;
  405. } else {
  406. return e;
  407. }
  408. }).toList();
  409. _saveCache();
  410. return ret;
  411. }
  412. Future<bool> setTagColor(String tag, Color color) async {
  413. final ret = await current.setTagColor(tag, color);
  414. await pullNonLegacyAfterChange();
  415. _saveCache();
  416. return ret;
  417. }
  418. Future<bool> deleteTag(String tag) async {
  419. final ret = await current.deleteTag(tag);
  420. await pullNonLegacyAfterChange();
  421. _saveCache();
  422. return ret;
  423. }
  424. // #endregion
  425. // #region sync from recent
  426. Future<void> _syncFromRecent({bool push = true}) async {
  427. if (!_syncFromRecentLock) {
  428. _syncFromRecentLock = true;
  429. await _syncFromRecentWithoutLock(push: push);
  430. _syncFromRecentLock = false;
  431. }
  432. }
  433. Future<void> _syncFromRecentWithoutLock({bool push = true}) async {
  434. Future<List<Peer>> getRecentPeers() async {
  435. try {
  436. List<String> filteredPeerIDs;
  437. if (_syncAllFromRecent) {
  438. _syncAllFromRecent = false;
  439. filteredPeerIDs = [];
  440. } else {
  441. final new_stored_str = await bind.mainGetNewStoredPeers();
  442. if (new_stored_str.isEmpty) return [];
  443. filteredPeerIDs = (jsonDecode(new_stored_str) as List<dynamic>)
  444. .map((e) => e.toString())
  445. .toList();
  446. if (filteredPeerIDs.isEmpty) return [];
  447. }
  448. final loadStr = await bind.mainLoadRecentPeersForAb(
  449. filter: jsonEncode(filteredPeerIDs));
  450. if (loadStr.isEmpty) {
  451. return [];
  452. }
  453. List<dynamic> mapPeers = jsonDecode(loadStr);
  454. List<Peer> recents = List.empty(growable: true);
  455. for (var m in mapPeers) {
  456. if (m is Map<String, dynamic>) {
  457. recents.add(Peer.fromJson(m));
  458. }
  459. }
  460. return recents;
  461. } catch (e) {
  462. debugPrint('getRecentPeers: $e');
  463. }
  464. return [];
  465. }
  466. try {
  467. if (!shouldSyncAb()) return;
  468. final recents = await getRecentPeers();
  469. if (recents.isEmpty) return;
  470. debugPrint("sync from recent, len: ${recents.length}");
  471. if (current.canWrite() && current.initialized) {
  472. await current.syncFromRecent(recents);
  473. }
  474. } catch (e) {
  475. debugPrint('_syncFromRecentWithoutLock: $e');
  476. }
  477. }
  478. void setShouldAsync(bool v) async {
  479. await bind.mainSetLocalOption(
  480. key: syncAbOption, value: v ? 'Y' : defaultOptionNo);
  481. _syncAllFromRecent = true;
  482. _timerCounter = 0;
  483. }
  484. // #endregion
  485. // #region cache
  486. _saveCache() {
  487. try {
  488. var ab_entries = _serializeCache();
  489. Map<String, dynamic> m = <String, dynamic>{
  490. "access_token": bind.mainGetLocalOption(key: 'access_token'),
  491. "ab_entries": ab_entries,
  492. };
  493. bind.mainSaveAb(json: jsonEncode(m));
  494. } catch (e) {
  495. debugPrint('ab save:$e');
  496. }
  497. }
  498. List<dynamic> _serializeCache() {
  499. var res = [];
  500. addressbooks.forEach((key, value) {
  501. if (!value.isPersonal() && key != current.name()) return;
  502. res.add({
  503. "guid": value.sharedProfile()?.guid ?? '',
  504. "name": key,
  505. "tags": value.tags,
  506. "peers": value.peers
  507. .map((e) => e.toCustomJson(includingHash: value.isPersonal()))
  508. .toList(),
  509. "tag_colors": jsonEncode(value.tagColors)
  510. });
  511. });
  512. return res;
  513. }
  514. trySetCurrentToLast() {
  515. final name = bind.getLocalFlutterOption(k: kOptionCurrentAbName);
  516. if (addressbooks.containsKey(name)) {
  517. _currentName.value = name;
  518. }
  519. }
  520. Future<void> loadCache() async {
  521. try {
  522. if (_cacheLoadOnceFlag || currentAbLoading.value) return;
  523. _cacheLoadOnceFlag = true;
  524. final access_token = bind.mainGetLocalOption(key: 'access_token');
  525. if (access_token.isEmpty) return;
  526. final cache = await bind.mainLoadAb();
  527. if (currentAbLoading.value) return;
  528. final data = jsonDecode(cache);
  529. if (data == null || data['access_token'] != access_token) return;
  530. _deserializeCache(data);
  531. legacyMode.value = addressbooks.containsKey(_legacyAddressBookName);
  532. trySetCurrentToLast();
  533. } catch (e) {
  534. debugPrint("load ab cache: $e");
  535. }
  536. }
  537. _deserializeCache(dynamic data) {
  538. if (data == null) return;
  539. reset();
  540. final abEntries = data['ab_entries'];
  541. if (abEntries is List) {
  542. for (var i = 0; i < abEntries.length; i++) {
  543. var abEntry = abEntries[i];
  544. if (abEntry is Map<String, dynamic>) {
  545. var guid = abEntry['guid'];
  546. var name = abEntry['name'];
  547. final BaseAb ab;
  548. if (name == _legacyAddressBookName) {
  549. ab = LegacyAb();
  550. } else {
  551. if (name == null || guid == null) {
  552. continue;
  553. }
  554. ab = Ab(AbProfile(guid, name, '', '', ShareRule.read.value),
  555. name == _personalAddressBookName);
  556. }
  557. addressbooks[name] = ab;
  558. if (abEntry['tags'] is List) {
  559. ab.tags.value =
  560. (abEntry['tags'] as List).map((e) => e.toString()).toList();
  561. }
  562. if (abEntry['peers'] is List) {
  563. for (var peer in abEntry['peers']) {
  564. ab.peers.add(Peer.fromJson(peer));
  565. }
  566. }
  567. if (abEntry['tag_colors'] is String) {
  568. Map<String, dynamic> map = jsonDecode(abEntry['tag_colors']);
  569. ab.tagColors.value = Map<String, int>.from(map);
  570. }
  571. }
  572. }
  573. }
  574. }
  575. // #endregion
  576. // #region tools
  577. Peer? find(String id) {
  578. return currentAbPeers.firstWhereOrNull((e) => e.id == id);
  579. }
  580. bool idContainByCurrent(String id) {
  581. return currentAbPeers.where((element) => element.id == id).isNotEmpty;
  582. }
  583. void unsetSelectedTags() {
  584. selectedTags.clear();
  585. }
  586. List<dynamic> getPeerTags(String id) {
  587. final it = currentAbPeers.where((p0) => p0.id == id);
  588. if (it.isEmpty) {
  589. return [];
  590. } else {
  591. return it.first.tags;
  592. }
  593. }
  594. Color getCurrentAbTagColor(String tag) {
  595. int? colorValue = current.tagColors[tag];
  596. if (colorValue != null) {
  597. return Color(colorValue);
  598. }
  599. return str2color2(tag, existing: current.tagColors.values.toList());
  600. }
  601. List<String> addressBookNames() {
  602. return addressbooks.keys.toList();
  603. }
  604. String personalAddressBookName() {
  605. return _personalAddressBookName;
  606. }
  607. Future<void> setCurrentName(String name) async {
  608. final oldName = _currentName.value;
  609. if (addressbooks.containsKey(name)) {
  610. _currentName.value = name;
  611. } else {
  612. if (addressbooks.containsKey(_personalAddressBookName)) {
  613. _currentName.value = _personalAddressBookName;
  614. } else if (addressbooks.containsKey(_legacyAddressBookName)) {
  615. _currentName.value = _legacyAddressBookName;
  616. } else {
  617. _currentName.value = '';
  618. }
  619. }
  620. if (!current.initialized) {
  621. await current.pullAb(quiet: false);
  622. }
  623. _refreshTab();
  624. if (oldName != _currentName.value) {
  625. _syncAllFromRecent = true;
  626. _saveCache();
  627. }
  628. }
  629. bool isCurrentAbFull(bool warn) {
  630. final res = current.isFull();
  631. if (res && warn) {
  632. BotToast.showText(
  633. contentColor: Colors.red, text: translate('exceed_max_devices'));
  634. }
  635. return res;
  636. }
  637. void _refreshTab() {
  638. platformFFI.tryHandle({'name': LoadEvent.addressBook});
  639. }
  640. // should not call this function in a loop call stack
  641. Future<void> pullNonLegacyAfterChange({String? name}) async {
  642. if (name == null) {
  643. if (current.name() != _legacyAddressBookName) {
  644. return await current.pullAb(quiet: true);
  645. }
  646. } else if (name != _legacyAddressBookName) {
  647. final ab = addressbooks[name];
  648. if (ab != null) {
  649. return await ab.pullAb(quiet: true);
  650. }
  651. }
  652. }
  653. List<String> idExistIn(String id) {
  654. List<String> v = [];
  655. addressbooks.forEach((key, value) {
  656. if (value.peers.any((e) => e.id == id)) {
  657. v.add(key);
  658. }
  659. });
  660. return v;
  661. }
  662. List<Peer> allPeers() {
  663. List<Peer> v = [];
  664. addressbooks.forEach((key, value) {
  665. v.addAll(value.peers.map((e) => Peer.copy(e)).toList());
  666. });
  667. return v;
  668. }
  669. String translatedName(String name) {
  670. if (name == _personalAddressBookName || name == _legacyAddressBookName) {
  671. return translate(name);
  672. } else {
  673. return name;
  674. }
  675. }
  676. // #endregion
  677. }
  678. abstract class BaseAb {
  679. final peers = List<Peer>.empty(growable: true).obs;
  680. final RxList<String> tags = <String>[].obs;
  681. final RxMap<String, int> tagColors = Map<String, int>.fromEntries([]).obs;
  682. final selectedTags = List<String>.empty(growable: true).obs;
  683. final pullError = "".obs;
  684. final pushError = "".obs;
  685. final abLoading = false.obs;
  686. bool initialized = false;
  687. String name();
  688. bool isPersonal() {
  689. return name() == _personalAddressBookName ||
  690. name() == _legacyAddressBookName;
  691. }
  692. bool isLegacy() {
  693. return name() == _legacyAddressBookName;
  694. }
  695. Future<void> pullAb({quiet = false}) async {
  696. debugPrint("pull ab \"${name()}\"");
  697. if (abLoading.value) return;
  698. if (!quiet) {
  699. abLoading.value = true;
  700. pullError.value = "";
  701. }
  702. initialized = false;
  703. try {
  704. initialized = await pullAbImpl(quiet: quiet);
  705. } catch (_) {}
  706. abLoading.value = false;
  707. }
  708. Future<bool> pullAbImpl({quiet = false});
  709. Future<String?> addPeers(List<Map<String, dynamic>> ps);
  710. removeHash(Map<String, dynamic> p) {
  711. p.remove('hash');
  712. }
  713. removePassword(Map<String, dynamic> p) {
  714. p.remove('password');
  715. }
  716. Future<bool> changeTagForPeers(List<String> ids, List<dynamic> tags);
  717. Future<bool> changeAlias({required String id, required String alias});
  718. Future<bool> changePersonalHashPassword(String id, String hash);
  719. Future<bool> changeSharedPassword(String id, String password);
  720. Future<bool> deletePeers(List<String> ids);
  721. Future<bool> addTags(List<String> tagList, Map<String, int> tagColorMap);
  722. bool tagContainBy(String tag) {
  723. return tags.where((element) => element == tag).isNotEmpty;
  724. }
  725. Future<bool> renameTag(String oldTag, String newTag);
  726. Future<bool> setTagColor(String tag, Color color);
  727. Future<bool> deleteTag(String tag);
  728. bool isFull();
  729. void setSharedProfile(AbProfile profile);
  730. AbProfile? sharedProfile();
  731. bool canWrite();
  732. bool fullControl();
  733. Future<void> syncFromRecent(List<Peer> recents);
  734. }
  735. class LegacyAb extends BaseAb {
  736. bool get emtpy => peers.isEmpty && tags.isEmpty;
  737. // licensedDevices is obtained from personal ab, shared ab restrict it in server
  738. var licensedDevices = 0;
  739. LegacyAb();
  740. @override
  741. AbProfile? sharedProfile() {
  742. return null;
  743. }
  744. @override
  745. void setSharedProfile(AbProfile? profile) {}
  746. @override
  747. bool canWrite() {
  748. return true;
  749. }
  750. @override
  751. bool fullControl() {
  752. return true;
  753. }
  754. @override
  755. bool isFull() {
  756. return licensedDevices > 0 && peers.length >= licensedDevices;
  757. }
  758. @override
  759. String name() {
  760. return _legacyAddressBookName;
  761. }
  762. @override
  763. Future<bool> pullAbImpl({quiet = false}) async {
  764. bool ret = false;
  765. final api = "${await bind.mainGetApiServer()}/api/ab";
  766. int? statusCode;
  767. try {
  768. var authHeaders = getHttpHeaders();
  769. authHeaders['Content-Type'] = "application/json";
  770. authHeaders['Accept-Encoding'] = "gzip";
  771. final resp = await http.get(Uri.parse(api), headers: authHeaders);
  772. statusCode = resp.statusCode;
  773. if (resp.body.toLowerCase() == "null") {
  774. // normal reply, empty ab return null
  775. tags.clear();
  776. tagColors.clear();
  777. peers.clear();
  778. } else if (resp.body.isNotEmpty) {
  779. Map<String, dynamic> json =
  780. _jsonDecodeRespMap(utf8.decode(resp.bodyBytes), resp.statusCode);
  781. if (json.containsKey('error')) {
  782. throw json['error'];
  783. } else if (json.containsKey('data')) {
  784. try {
  785. licensedDevices = json['licensed_devices'];
  786. // ignore: empty_catches
  787. } catch (e) {}
  788. final data = jsonDecode(json['data']);
  789. if (data != null) {
  790. _deserialize(data);
  791. }
  792. ret = true;
  793. }
  794. }
  795. } catch (err) {
  796. if (!quiet) {
  797. pullError.value =
  798. '${translate('pull_ab_failed_tip')}: ${translate(err.toString())}';
  799. }
  800. } finally {
  801. if (pullError.isNotEmpty) {
  802. if (statusCode == 401) {
  803. gFFI.userModel.reset(resetOther: true);
  804. }
  805. }
  806. }
  807. return ret;
  808. }
  809. Future<bool> pushAb(
  810. {bool toastIfFail = true, bool toastIfSucc = true}) async {
  811. debugPrint("pushAb: toastIfFail:$toastIfFail, toastIfSucc:$toastIfSucc");
  812. if (!gFFI.userModel.isLogin) return false;
  813. pushError.value = '';
  814. bool ret = false;
  815. try {
  816. //https: //stackoverflow.com/questions/68249333/flutter-getx-updating-item-in-children-list-is-not-reactive
  817. peers.refresh();
  818. final api = "${await bind.mainGetApiServer()}/api/ab";
  819. var authHeaders = getHttpHeaders();
  820. authHeaders['Content-Type'] = "application/json";
  821. final body = jsonEncode({"data": jsonEncode(_serialize())});
  822. http.Response resp;
  823. // support compression
  824. if (licensedDevices > 0 && body.length > 1024) {
  825. authHeaders['Content-Encoding'] = "gzip";
  826. resp = await http.post(Uri.parse(api),
  827. headers: authHeaders, body: GZipCodec().encode(utf8.encode(body)));
  828. } else {
  829. resp =
  830. await http.post(Uri.parse(api), headers: authHeaders, body: body);
  831. }
  832. if (resp.statusCode == 200 &&
  833. (resp.body.isEmpty || resp.body.toLowerCase() == 'null')) {
  834. ret = true;
  835. } else {
  836. Map<String, dynamic> json =
  837. _jsonDecodeRespMap(utf8.decode(resp.bodyBytes), resp.statusCode);
  838. if (json.containsKey('error')) {
  839. throw json['error'];
  840. } else if (resp.statusCode == 200) {
  841. ret = true;
  842. } else {
  843. throw 'HTTP ${resp.statusCode}';
  844. }
  845. }
  846. } catch (e) {
  847. pushError.value =
  848. '${translate('push_ab_failed_tip')}: ${translate(e.toString())}';
  849. }
  850. if (!ret && toastIfFail) {
  851. BotToast.showText(contentColor: Colors.red, text: pushError.value);
  852. }
  853. if (ret && toastIfSucc) {
  854. showToast(translate('Successful'));
  855. }
  856. return ret;
  857. }
  858. // #region Peer
  859. @override
  860. Future<String?> addPeers(List<Map<String, dynamic>> ps) async {
  861. bool full = false;
  862. for (var p in ps) {
  863. if (!isFull()) {
  864. p.remove('password'); // legacy ab ignore password
  865. final index = peers.indexWhere((e) => e.id == p['id']);
  866. if (index >= 0) {
  867. _merge(Peer.fromJson(p), peers[index]);
  868. _mergePeerFromGroup(peers[index]);
  869. } else {
  870. peers.add(Peer.fromJson(p));
  871. }
  872. } else {
  873. full = true;
  874. break;
  875. }
  876. }
  877. if (!await pushAb()) {
  878. return "Failed to push to server";
  879. } else if (full) {
  880. return translate("exceed_max_devices");
  881. } else {
  882. return null;
  883. }
  884. }
  885. _mergePeerFromGroup(Peer p) {
  886. final g = gFFI.groupModel.peers.firstWhereOrNull((e) => p.id == e.id);
  887. if (g == null) return;
  888. if (p.username.isEmpty) {
  889. p.username = g.username;
  890. }
  891. if (p.hostname.isEmpty) {
  892. p.hostname = g.hostname;
  893. }
  894. if (p.platform.isEmpty) {
  895. p.platform = g.platform;
  896. }
  897. }
  898. @override
  899. Future<bool> changeTagForPeers(List<String> ids, List<dynamic> tags) async {
  900. peers.map((e) {
  901. if (ids.contains(e.id)) {
  902. e.tags = tags;
  903. }
  904. }).toList();
  905. return await pushAb();
  906. }
  907. @override
  908. Future<bool> changeAlias({required String id, required String alias}) async {
  909. final it = peers.where((element) => element.id == id);
  910. if (it.isEmpty) {
  911. return false;
  912. }
  913. it.first.alias = alias;
  914. return await pushAb();
  915. }
  916. @override
  917. Future<bool> changeSharedPassword(String id, String password) async {
  918. // no need to implement
  919. return false;
  920. }
  921. @override
  922. Future<void> syncFromRecent(List<Peer> recents) async {
  923. bool peerSyncEqual(Peer a, Peer b) {
  924. return a.hash == b.hash &&
  925. a.username == b.username &&
  926. a.platform == b.platform &&
  927. a.hostname == b.hostname &&
  928. a.alias == b.alias;
  929. }
  930. bool needSync = false;
  931. for (var i = 0; i < recents.length; i++) {
  932. var r = recents[i];
  933. var index = peers.indexWhere((e) => e.id == r.id);
  934. if (index < 0) {
  935. if (!isFull()) {
  936. peers.add(r);
  937. needSync = true;
  938. }
  939. } else {
  940. Peer old = Peer.copy(peers[index]);
  941. _merge(r, peers[index]);
  942. if (!peerSyncEqual(peers[index], old)) {
  943. needSync = true;
  944. }
  945. }
  946. }
  947. if (needSync) {
  948. await pushAb(toastIfSucc: false, toastIfFail: false);
  949. gFFI.abModel._refreshTab();
  950. }
  951. // Pull cannot be used for sync to avoid cyclic sync.
  952. }
  953. void _merge(Peer r, Peer p) {
  954. p.hash = r.hash.isEmpty ? p.hash : r.hash;
  955. p.username = r.username.isEmpty ? p.username : r.username;
  956. p.hostname = r.hostname.isEmpty ? p.hostname : r.hostname;
  957. p.platform = r.platform.isEmpty ? p.platform : r.platform;
  958. p.alias = p.alias.isEmpty ? r.alias : p.alias;
  959. }
  960. @override
  961. Future<bool> changePersonalHashPassword(String id, String hash) async {
  962. bool changed = false;
  963. final it = peers.where((element) => element.id == id);
  964. if (it.isNotEmpty) {
  965. if (it.first.hash != hash) {
  966. it.first.hash = hash;
  967. changed = true;
  968. }
  969. }
  970. if (changed) {
  971. return await pushAb(toastIfSucc: false, toastIfFail: false);
  972. }
  973. return true;
  974. }
  975. @override
  976. Future<bool> deletePeers(List<String> ids) async {
  977. peers.removeWhere((e) => ids.contains(e.id));
  978. return await pushAb();
  979. }
  980. // #endregion
  981. // #region Tag
  982. @override
  983. Future<bool> addTags(
  984. List<String> tagList, Map<String, int> tagColorMap) async {
  985. for (var e in tagList) {
  986. if (!tagContainBy(e)) {
  987. tags.add(e);
  988. }
  989. if (tagColors[e] == null) {
  990. tagColors[e] = str2color2(e, existing: tagColors.values.toList()).value;
  991. }
  992. }
  993. return await pushAb();
  994. }
  995. @override
  996. Future<bool> renameTag(String oldTag, String newTag) async {
  997. if (tags.contains(newTag)) {
  998. BotToast.showText(
  999. contentColor: Colors.red, text: 'Tag $newTag already exists');
  1000. return false;
  1001. }
  1002. tags.value = tags.map((e) {
  1003. if (e == oldTag) {
  1004. return newTag;
  1005. } else {
  1006. return e;
  1007. }
  1008. }).toList();
  1009. for (var peer in peers) {
  1010. peer.tags = peer.tags.map((e) {
  1011. if (e == oldTag) {
  1012. return newTag;
  1013. } else {
  1014. return e;
  1015. }
  1016. }).toList();
  1017. }
  1018. int? oldColor = tagColors[oldTag];
  1019. if (oldColor != null) {
  1020. tagColors.remove(oldTag);
  1021. tagColors.addAll({newTag: oldColor});
  1022. }
  1023. return await pushAb();
  1024. }
  1025. @override
  1026. Future<bool> setTagColor(String tag, Color color) async {
  1027. if (tags.contains(tag)) {
  1028. tagColors[tag] = color.value;
  1029. }
  1030. return await pushAb();
  1031. }
  1032. @override
  1033. Future<bool> deleteTag(String tag) async {
  1034. gFFI.abModel.selectedTags.remove(tag);
  1035. tags.removeWhere((element) => element == tag);
  1036. tagColors.remove(tag);
  1037. for (var peer in peers) {
  1038. if (peer.tags.isEmpty) {
  1039. continue;
  1040. }
  1041. if (peer.tags.contains(tag)) {
  1042. peer.tags.remove(tag);
  1043. }
  1044. }
  1045. return await pushAb();
  1046. }
  1047. // #endregion
  1048. Map<String, dynamic> _serialize() {
  1049. final peersJsonData =
  1050. peers.map((e) => e.toCustomJson(includingHash: true)).toList();
  1051. for (var e in tags) {
  1052. if (tagColors[e] == null) {
  1053. tagColors[e] = str2color2(e, existing: tagColors.values.toList()).value;
  1054. }
  1055. }
  1056. final tagColorJsonData = jsonEncode(tagColors);
  1057. return {
  1058. "tags": tags,
  1059. "peers": peersJsonData,
  1060. "tag_colors": tagColorJsonData
  1061. };
  1062. }
  1063. _deserialize(dynamic data) {
  1064. if (data == null) return;
  1065. final oldOnlineIDs = peers.where((e) => e.online).map((e) => e.id).toList();
  1066. tags.clear();
  1067. tagColors.clear();
  1068. peers.clear();
  1069. if (data['tags'] is List) {
  1070. tags.value = (data['tags'] as List).map((e) => e.toString()).toList();
  1071. }
  1072. if (data['peers'] is List) {
  1073. for (final peer in data['peers']) {
  1074. peers.add(Peer.fromJson(peer));
  1075. }
  1076. }
  1077. if (isFull()) {
  1078. peers.removeRange(licensedDevices, peers.length);
  1079. }
  1080. // restore online
  1081. peers
  1082. .where((e) => oldOnlineIDs.contains(e.id))
  1083. .map((e) => e.online = true)
  1084. .toList();
  1085. if (data['tag_colors'] is String) {
  1086. Map<String, dynamic> map = jsonDecode(data['tag_colors']);
  1087. tagColors.value = Map<String, int>.from(map);
  1088. }
  1089. // add color to tag
  1090. final tagsWithoutColor =
  1091. tags.toList().where((e) => !tagColors.containsKey(e)).toList();
  1092. for (var t in tagsWithoutColor) {
  1093. tagColors[t] = str2color2(t, existing: tagColors.values.toList()).value;
  1094. }
  1095. }
  1096. }
  1097. class Ab extends BaseAb {
  1098. AbProfile profile;
  1099. late final bool personal;
  1100. bool get emtpy => peers.isEmpty && tags.isEmpty;
  1101. Ab(this.profile, this.personal);
  1102. @override
  1103. String name() {
  1104. if (personal) {
  1105. return _personalAddressBookName;
  1106. } else {
  1107. return profile.name;
  1108. }
  1109. }
  1110. @override
  1111. AbProfile? sharedProfile() {
  1112. return profile;
  1113. }
  1114. @override
  1115. void setSharedProfile(AbProfile profile) {
  1116. this.profile = profile;
  1117. }
  1118. @override
  1119. bool isFull() {
  1120. return gFFI.abModel._maxPeerOneAb > 0 &&
  1121. peers.length >= gFFI.abModel._maxPeerOneAb;
  1122. }
  1123. @override
  1124. bool canWrite() {
  1125. if (personal) {
  1126. return true;
  1127. } else {
  1128. return profile.rule == ShareRule.readWrite.value ||
  1129. profile.rule == ShareRule.fullControl.value;
  1130. }
  1131. }
  1132. @override
  1133. bool fullControl() {
  1134. if (personal) {
  1135. return true;
  1136. } else {
  1137. return profile.rule == ShareRule.fullControl.value;
  1138. }
  1139. }
  1140. @override
  1141. Future<bool> pullAbImpl({quiet = false}) async {
  1142. bool ret = true;
  1143. List<Peer> tmpPeers = [];
  1144. if (!await _fetchPeers(tmpPeers, quiet: quiet)) {
  1145. ret = false;
  1146. }
  1147. peers.value = tmpPeers;
  1148. List<AbTag> tmpTags = [];
  1149. if (!await _fetchTags(tmpTags, quiet: quiet)) {
  1150. ret = false;
  1151. }
  1152. tags.value = tmpTags.map((e) => e.name).toList();
  1153. Map<String, int> tmpTagColors = {};
  1154. for (var t in tmpTags) {
  1155. tmpTagColors[t.name] = t.color;
  1156. }
  1157. tagColors.value = tmpTagColors;
  1158. return ret;
  1159. }
  1160. Future<bool> _fetchPeers(List<Peer> tmpPeers, {quiet = false}) async {
  1161. final api = "${await bind.mainGetApiServer()}/api/ab/peers";
  1162. int? statusCode;
  1163. try {
  1164. var uri0 = Uri.parse(api);
  1165. final pageSize = 100;
  1166. var total = 0;
  1167. int current = 0;
  1168. do {
  1169. current += 1;
  1170. var uri = Uri(
  1171. scheme: uri0.scheme,
  1172. host: uri0.host,
  1173. path: uri0.path,
  1174. port: uri0.port,
  1175. queryParameters: {
  1176. 'current': current.toString(),
  1177. 'pageSize': pageSize.toString(),
  1178. 'ab': profile.guid,
  1179. });
  1180. var headers = getHttpHeaders();
  1181. headers['Content-Type'] = "application/json";
  1182. final resp = await http.post(uri, headers: headers);
  1183. statusCode = resp.statusCode;
  1184. Map<String, dynamic> json =
  1185. _jsonDecodeRespMap(utf8.decode(resp.bodyBytes), resp.statusCode);
  1186. if (json.containsKey('error')) {
  1187. throw json['error'];
  1188. }
  1189. if (resp.statusCode != 200) {
  1190. throw 'HTTP ${resp.statusCode}';
  1191. }
  1192. if (json.containsKey('total')) {
  1193. if (total == 0) total = json['total'];
  1194. if (json.containsKey('data')) {
  1195. final data = json['data'];
  1196. if (data is List) {
  1197. for (final profile in data) {
  1198. final u = Peer.fromJson(profile);
  1199. int index = tmpPeers.indexWhere((e) => e.id == u.id);
  1200. if (index < 0) {
  1201. tmpPeers.add(u);
  1202. } else {
  1203. tmpPeers[index] = u;
  1204. }
  1205. }
  1206. }
  1207. }
  1208. }
  1209. } while (current * pageSize < total);
  1210. return true;
  1211. } catch (err) {
  1212. if (!quiet) {
  1213. pullError.value =
  1214. '${translate('pull_ab_failed_tip')}: ${translate(err.toString())}';
  1215. }
  1216. } finally {
  1217. if (pullError.isNotEmpty) {
  1218. if (statusCode == 401) {
  1219. gFFI.userModel.reset(resetOther: true);
  1220. }
  1221. }
  1222. }
  1223. return false;
  1224. }
  1225. Future<bool> _fetchTags(List<AbTag> tmpTags, {quiet = false}) async {
  1226. final api = "${await bind.mainGetApiServer()}/api/ab/tags/${profile.guid}";
  1227. int? statusCode;
  1228. try {
  1229. var uri0 = Uri.parse(api);
  1230. var uri = Uri(
  1231. scheme: uri0.scheme,
  1232. host: uri0.host,
  1233. path: uri0.path,
  1234. port: uri0.port,
  1235. );
  1236. var headers = getHttpHeaders();
  1237. headers['Content-Type'] = "application/json";
  1238. final resp = await http.post(uri, headers: headers);
  1239. statusCode = resp.statusCode;
  1240. List<dynamic> json =
  1241. _jsonDecodeRespList(utf8.decode(resp.bodyBytes), resp.statusCode);
  1242. if (resp.statusCode != 200) {
  1243. throw 'HTTP ${resp.statusCode}';
  1244. }
  1245. for (final d in json) {
  1246. final t = AbTag.fromJson(d);
  1247. int index = tmpTags.indexWhere((e) => e.name == t.name);
  1248. if (index < 0) {
  1249. tmpTags.add(t);
  1250. } else {
  1251. tmpTags[index] = t;
  1252. }
  1253. }
  1254. return true;
  1255. } catch (err) {
  1256. if (!quiet) {
  1257. pullError.value =
  1258. '${translate('pull_ab_failed_tip')}: ${translate(err.toString())}';
  1259. }
  1260. } finally {
  1261. if (pullError.isNotEmpty) {
  1262. if (statusCode == 401) {
  1263. gFFI.userModel.reset(resetOther: true);
  1264. }
  1265. }
  1266. }
  1267. return false;
  1268. }
  1269. // #region Peers
  1270. @override
  1271. Future<String?> addPeers(List<Map<String, dynamic>> ps) async {
  1272. try {
  1273. final api =
  1274. "${await bind.mainGetApiServer()}/api/ab/peer/add/${profile.guid}";
  1275. var headers = getHttpHeaders();
  1276. headers['Content-Type'] = "application/json";
  1277. for (var p in ps) {
  1278. if (peers.firstWhereOrNull((e) => e.id == p['id']) != null) {
  1279. continue;
  1280. }
  1281. if (isFull()) {
  1282. return translate("exceed_max_devices");
  1283. }
  1284. if (personal) {
  1285. removePassword(p);
  1286. } else {
  1287. removeHash(p);
  1288. }
  1289. String body = jsonEncode(p);
  1290. final resp =
  1291. await http.post(Uri.parse(api), headers: headers, body: body);
  1292. final errMsg = _jsonDecodeActionResp(resp);
  1293. if (errMsg.isNotEmpty) {
  1294. return errMsg;
  1295. }
  1296. }
  1297. } catch (err) {
  1298. return err.toString();
  1299. }
  1300. return null;
  1301. }
  1302. @override
  1303. Future<bool> changeTagForPeers(List<String> ids, List<dynamic> tags) async {
  1304. try {
  1305. final api =
  1306. "${await bind.mainGetApiServer()}/api/ab/peer/update/${profile.guid}";
  1307. var headers = getHttpHeaders();
  1308. headers['Content-Type'] = "application/json";
  1309. var ret = true;
  1310. for (var id in ids) {
  1311. final body = jsonEncode({"id": id, "tags": tags});
  1312. final resp =
  1313. await http.put(Uri.parse(api), headers: headers, body: body);
  1314. final errMsg = _jsonDecodeActionResp(resp);
  1315. if (errMsg.isNotEmpty) {
  1316. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1317. ret = false;
  1318. break;
  1319. }
  1320. }
  1321. return ret;
  1322. } catch (err) {
  1323. debugPrint('changeTagForPeers err: ${err.toString()}');
  1324. return false;
  1325. }
  1326. }
  1327. @override
  1328. Future<bool> changeAlias({required String id, required String alias}) async {
  1329. try {
  1330. final api =
  1331. "${await bind.mainGetApiServer()}/api/ab/peer/update/${profile.guid}";
  1332. var headers = getHttpHeaders();
  1333. headers['Content-Type'] = "application/json";
  1334. final body = jsonEncode({"id": id, "alias": alias});
  1335. final resp = await http.put(Uri.parse(api), headers: headers, body: body);
  1336. final errMsg = _jsonDecodeActionResp(resp);
  1337. if (errMsg.isNotEmpty) {
  1338. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1339. return false;
  1340. }
  1341. return true;
  1342. } catch (err) {
  1343. debugPrint('changeAlias err: ${err.toString()}');
  1344. return false;
  1345. }
  1346. }
  1347. Future<bool> _setPassword(Object bodyContent) async {
  1348. try {
  1349. final api =
  1350. "${await bind.mainGetApiServer()}/api/ab/peer/update/${profile.guid}";
  1351. var headers = getHttpHeaders();
  1352. headers['Content-Type'] = "application/json";
  1353. final body = jsonEncode(bodyContent);
  1354. final resp = await http.put(Uri.parse(api), headers: headers, body: body);
  1355. final errMsg = _jsonDecodeActionResp(resp);
  1356. if (errMsg.isNotEmpty) {
  1357. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1358. return false;
  1359. }
  1360. return true;
  1361. } catch (err) {
  1362. debugPrint('changeSharedPassword err: ${err.toString()}');
  1363. return false;
  1364. }
  1365. }
  1366. @override
  1367. Future<bool> changePersonalHashPassword(String id, String hash) async {
  1368. if (!personal) return false;
  1369. if (!peers.any((e) => e.id == id)) return true;
  1370. return await _setPassword({"id": id, "hash": hash});
  1371. }
  1372. @override
  1373. Future<bool> changeSharedPassword(String id, String password) async {
  1374. if (personal) return false;
  1375. return await _setPassword({"id": id, "password": password});
  1376. }
  1377. @override
  1378. Future<void> syncFromRecent(List<Peer> recents) async {
  1379. bool uiUpdate = false;
  1380. bool saveCache = false;
  1381. final api =
  1382. "${await bind.mainGetApiServer()}/api/ab/peer/update/${profile.guid}";
  1383. var headers = getHttpHeaders();
  1384. headers['Content-Type'] = "application/json";
  1385. Future<bool> trySyncOnePeer(Peer p, Peer r) async {
  1386. var map = Map<String, String>.fromEntries([]);
  1387. if (p.sameServer != true &&
  1388. r.username.isNotEmpty &&
  1389. p.username != r.username) {
  1390. p.username = r.username;
  1391. map['username'] = r.username;
  1392. }
  1393. if (p.sameServer != true &&
  1394. r.hostname.isNotEmpty &&
  1395. p.hostname != r.hostname) {
  1396. p.hostname = r.hostname;
  1397. map['hostname'] = r.hostname;
  1398. }
  1399. if (p.sameServer != true &&
  1400. r.platform.isNotEmpty &&
  1401. p.platform != r.platform) {
  1402. p.platform = r.platform;
  1403. map['platform'] = r.platform;
  1404. }
  1405. if (personal && r.hash.isNotEmpty && p.hash != r.hash) {
  1406. p.hash = r.hash;
  1407. map['hash'] = r.hash;
  1408. saveCache = true;
  1409. }
  1410. if (map.isEmpty) {
  1411. // no need to sync
  1412. return false;
  1413. }
  1414. map['id'] = p.id;
  1415. final body = jsonEncode(map);
  1416. final resp = await http.put(Uri.parse(api), headers: headers, body: body);
  1417. final errMsg = _jsonDecodeActionResp(resp);
  1418. if (errMsg.isNotEmpty) {
  1419. debugPrint('syncOnePeer errMsg: $errMsg');
  1420. return false;
  1421. }
  1422. uiUpdate = true;
  1423. return true;
  1424. }
  1425. try {
  1426. // Not add new peers because IDs that are not on the server can't be synced, then sync will happen every startup.
  1427. for (var p in peers) {
  1428. Peer? r = recents.firstWhereOrNull((e) => e.id == p.id);
  1429. if (r != null) {
  1430. await trySyncOnePeer(p, r);
  1431. }
  1432. }
  1433. // Pull cannot be used for sync to avoid cyclic sync.
  1434. if (uiUpdate && gFFI.abModel.currentName.value == profile.name) {
  1435. peers.refresh();
  1436. }
  1437. if (saveCache) {
  1438. gFFI.abModel._saveCache();
  1439. }
  1440. } catch (err) {
  1441. debugPrint('syncFromRecent err: ${err.toString()}');
  1442. }
  1443. }
  1444. @override
  1445. Future<bool> deletePeers(List<String> ids) async {
  1446. try {
  1447. final api =
  1448. "${await bind.mainGetApiServer()}/api/ab/peer/${profile.guid}";
  1449. var headers = getHttpHeaders();
  1450. headers['Content-Type'] = "application/json";
  1451. final body = jsonEncode(ids);
  1452. final resp =
  1453. await http.delete(Uri.parse(api), headers: headers, body: body);
  1454. final errMsg = _jsonDecodeActionResp(resp);
  1455. if (errMsg.isNotEmpty) {
  1456. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1457. return false;
  1458. }
  1459. return true;
  1460. } catch (err) {
  1461. debugPrint('deletePeers err: ${err.toString()}');
  1462. return false;
  1463. }
  1464. }
  1465. // #endregion
  1466. // #region Tags
  1467. @override
  1468. Future<bool> addTags(
  1469. List<String> tagList, Map<String, int> tagColorMap) async {
  1470. try {
  1471. final api =
  1472. "${await bind.mainGetApiServer()}/api/ab/tag/add/${profile.guid}";
  1473. var headers = getHttpHeaders();
  1474. headers['Content-Type'] = "application/json";
  1475. for (var t in tagList) {
  1476. final body = jsonEncode({
  1477. "name": t,
  1478. "color": tagColorMap[t] ??
  1479. str2color2(t, existing: tagColors.values.toList()).value,
  1480. });
  1481. final resp =
  1482. await http.post(Uri.parse(api), headers: headers, body: body);
  1483. final errMsg = _jsonDecodeActionResp(resp);
  1484. if (errMsg.isNotEmpty) {
  1485. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1486. return false;
  1487. }
  1488. }
  1489. return true;
  1490. } catch (err) {
  1491. debugPrint('addTags err: ${err.toString()}');
  1492. return false;
  1493. }
  1494. }
  1495. @override
  1496. Future<bool> renameTag(String oldTag, String newTag) async {
  1497. if (tags.contains(newTag)) {
  1498. BotToast.showText(
  1499. contentColor: Colors.red, text: 'Tag $newTag already exists');
  1500. return false;
  1501. }
  1502. try {
  1503. final api =
  1504. "${await bind.mainGetApiServer()}/api/ab/tag/rename/${profile.guid}";
  1505. var headers = getHttpHeaders();
  1506. headers['Content-Type'] = "application/json";
  1507. final body = jsonEncode({
  1508. "old": oldTag,
  1509. "new": newTag,
  1510. });
  1511. final resp = await http.put(Uri.parse(api), headers: headers, body: body);
  1512. final errMsg = _jsonDecodeActionResp(resp);
  1513. if (errMsg.isNotEmpty) {
  1514. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1515. return false;
  1516. }
  1517. return true;
  1518. } catch (err) {
  1519. debugPrint('renameTag err: ${err.toString()}');
  1520. return false;
  1521. }
  1522. }
  1523. @override
  1524. Future<bool> setTagColor(String tag, Color color) async {
  1525. try {
  1526. final api =
  1527. "${await bind.mainGetApiServer()}/api/ab/tag/update/${profile.guid}";
  1528. var headers = getHttpHeaders();
  1529. headers['Content-Type'] = "application/json";
  1530. final body = jsonEncode({
  1531. "name": tag,
  1532. "color": color.value,
  1533. });
  1534. final resp = await http.put(Uri.parse(api), headers: headers, body: body);
  1535. final errMsg = _jsonDecodeActionResp(resp);
  1536. if (errMsg.isNotEmpty) {
  1537. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1538. return false;
  1539. }
  1540. return true;
  1541. } catch (err) {
  1542. debugPrint('setTagColor err: ${err.toString()}');
  1543. return false;
  1544. }
  1545. }
  1546. @override
  1547. Future<bool> deleteTag(String tag) async {
  1548. try {
  1549. final api = "${await bind.mainGetApiServer()}/api/ab/tag/${profile.guid}";
  1550. var headers = getHttpHeaders();
  1551. headers['Content-Type'] = "application/json";
  1552. final body = jsonEncode([tag]);
  1553. final resp =
  1554. await http.delete(Uri.parse(api), headers: headers, body: body);
  1555. final errMsg = _jsonDecodeActionResp(resp);
  1556. if (errMsg.isNotEmpty) {
  1557. BotToast.showText(contentColor: Colors.red, text: errMsg);
  1558. return false;
  1559. }
  1560. return true;
  1561. } catch (err) {
  1562. debugPrint('deleteTag err: ${err.toString()}');
  1563. return false;
  1564. }
  1565. }
  1566. // #endregion
  1567. }
  1568. // DummyAb is for current ab is null
  1569. class DummyAb extends BaseAb {
  1570. @override
  1571. bool isFull() {
  1572. return false;
  1573. }
  1574. @override
  1575. Future<String?> addPeers(List<Map<String, dynamic>> ps) async {
  1576. return "dummpy";
  1577. }
  1578. @override
  1579. Future<bool> addTags(
  1580. List<String> tagList, Map<String, int> tagColorMap) async {
  1581. return false;
  1582. }
  1583. @override
  1584. bool canWrite() {
  1585. return false;
  1586. }
  1587. @override
  1588. bool fullControl() {
  1589. return false;
  1590. }
  1591. @override
  1592. Future<bool> changeAlias({required String id, required String alias}) async {
  1593. return false;
  1594. }
  1595. @override
  1596. Future<bool> changePersonalHashPassword(String id, String hash) async {
  1597. return false;
  1598. }
  1599. @override
  1600. Future<bool> changeSharedPassword(String id, String password) async {
  1601. return false;
  1602. }
  1603. @override
  1604. Future<bool> changeTagForPeers(List<String> ids, List tags) async {
  1605. return false;
  1606. }
  1607. @override
  1608. Future<bool> deletePeers(List<String> ids) async {
  1609. return false;
  1610. }
  1611. @override
  1612. Future<bool> deleteTag(String tag) async {
  1613. return false;
  1614. }
  1615. @override
  1616. String name() {
  1617. return "dummpy";
  1618. }
  1619. @override
  1620. Future<bool> pullAbImpl({quiet = false}) async {
  1621. return false;
  1622. }
  1623. @override
  1624. Future<bool> renameTag(String oldTag, String newTag) async {
  1625. return false;
  1626. }
  1627. @override
  1628. Future<bool> setTagColor(String tag, Color color) async {
  1629. return false;
  1630. }
  1631. @override
  1632. AbProfile? sharedProfile() {
  1633. return null;
  1634. }
  1635. @override
  1636. void setSharedProfile(AbProfile profile) {}
  1637. @override
  1638. Future<void> syncFromRecent(List<Peer> recents) async {}
  1639. }
  1640. Map<String, dynamic> _jsonDecodeRespMap(String body, int statusCode) {
  1641. try {
  1642. Map<String, dynamic> json = jsonDecode(body);
  1643. return json;
  1644. } catch (e) {
  1645. final err = body.isNotEmpty && body.length < 128 ? body : e.toString();
  1646. if (statusCode != 200) {
  1647. throw 'HTTP $statusCode, $err';
  1648. }
  1649. throw err;
  1650. }
  1651. }
  1652. List<dynamic> _jsonDecodeRespList(String body, int statusCode) {
  1653. try {
  1654. List<dynamic> json = jsonDecode(body);
  1655. return json;
  1656. } catch (e) {
  1657. final err = body.isNotEmpty && body.length < 128 ? body : e.toString();
  1658. if (statusCode != 200) {
  1659. throw 'HTTP $statusCode, $err';
  1660. }
  1661. throw err;
  1662. }
  1663. }
  1664. String _jsonDecodeActionResp(http.Response resp) {
  1665. var errMsg = '';
  1666. if (resp.statusCode == 200 && resp.body.isEmpty) {
  1667. // ok
  1668. } else {
  1669. try {
  1670. errMsg = jsonDecode(resp.body)['error'].toString();
  1671. } catch (_) {}
  1672. if (errMsg.isEmpty) {
  1673. if (resp.statusCode != 200) {
  1674. errMsg = 'HTTP ${resp.statusCode}';
  1675. }
  1676. if (resp.body.isNotEmpty) {
  1677. if (errMsg.isNotEmpty) {
  1678. errMsg += ', ';
  1679. }
  1680. errMsg += resp.body;
  1681. }
  1682. if (errMsg.isEmpty) {
  1683. errMsg = "unknown error";
  1684. }
  1685. }
  1686. }
  1687. return errMsg;
  1688. }