ab_model.dart 53 KB

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