ab_model.dart 53 KB

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