ab_model.dart 52 KB

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