~cytrogen/fluent-reader-mobile

ref: e46dd4a5a6f0336196561790f696ca0cac06b9fb fluent-reader-mobile/lib/models/sync_model.dart -rw-r--r-- 1.8 KiB
e46dd4a5 — Bruce Liu add suggestions to editor 5 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import 'package:fluent_reader_lite/utils/global.dart';
import 'package:fluent_reader_lite/utils/store.dart';
import 'package:flutter/cupertino.dart';

class SyncModel with ChangeNotifier {
  bool hasService = Global.service != null;
  bool syncing = false;
  bool _lastSyncSuccess = Store.sp.getBool(StoreKeys.LAST_SYNC_SUCCESS) ?? true;
  DateTime _lastSynced = DateTime.fromMillisecondsSinceEpoch(
    Store.sp.getInt(StoreKeys.LAST_SYNCED) ?? 0
  );

  void checkHasService() {
    var value = Global.service != null;
    if (value != hasService) {
      hasService = value;
      notifyListeners();
    }
  }

  Future<void> removeService() async {
    if (syncing || Global.service == null) return;
    syncing = true;
    notifyListeners();
    var sids = Global.sourcesModel.getSources()
      .map((s) => s.id)
      .toList();
    await Global.sourcesModel.removeSources(sids);
    Global.service.remove();
    hasService = false;
    syncing = false;
    notifyListeners();
  }

  bool get lastSyncSuccess => _lastSyncSuccess;
  set lastSyncSuccess(bool value) {
    _lastSyncSuccess = value;
    Store.sp.setBool(StoreKeys.LAST_SYNC_SUCCESS, value);
  }

  DateTime get lastSynced => _lastSynced;
  set lastSynced(DateTime value) {
    _lastSynced = value;
    Store.sp.setInt(StoreKeys.LAST_SYNCED, value.millisecondsSinceEpoch);
  }

  Future<void> syncWithService() async {
    if (syncing || Global.service == null) return;
    syncing = true;
    notifyListeners();
    try {
      await Global.service.reauthenticate();
      await Global.sourcesModel.updateSources();
      await Global.itemsModel.syncItems();
      await Global.itemsModel.fetchItems();
      lastSyncSuccess = true;
    } catch(exp) {
      lastSyncSuccess = false;
      print(exp);
    }
    lastSynced = DateTime.now();
    syncing = false;
    notifyListeners();
  }
}