Welcome to mirror list, hosted at ThFree Co, Russian Federation.

NotesRepository.java « persistence « notes « owncloud « niedermann « it « java « main « src « app - github.com/stefan-niedermann/nextcloud-notes.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b52e59cbc1acfc9606a078a8f4693113dd5a7965 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
package it.niedermann.owncloud.notes.persistence;

import android.accounts.NetworkErrorException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.AnyThread;
import androidx.annotation.ColorInt;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.preference.PreferenceManager;

import com.nextcloud.android.sso.AccountImporter;
import com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException;
import com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException;
import com.nextcloud.android.sso.helper.SingleAccountHelper;
import com.nextcloud.android.sso.model.SingleSignOnAccount;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import it.niedermann.android.sharedpreferences.SharedPreferenceIntLiveData;
import it.niedermann.owncloud.notes.BuildConfig;
import it.niedermann.owncloud.notes.R;
import it.niedermann.owncloud.notes.edit.EditNoteActivity;
import it.niedermann.owncloud.notes.persistence.entity.Account;
import it.niedermann.owncloud.notes.persistence.entity.CategoryOptions;
import it.niedermann.owncloud.notes.persistence.entity.CategoryWithNotesCount;
import it.niedermann.owncloud.notes.persistence.entity.Note;
import it.niedermann.owncloud.notes.persistence.entity.NotesListWidgetData;
import it.niedermann.owncloud.notes.persistence.entity.SingleNoteWidgetData;
import it.niedermann.owncloud.notes.shared.model.ApiVersion;
import it.niedermann.owncloud.notes.shared.model.Capabilities;
import it.niedermann.owncloud.notes.shared.model.CategorySortingMethod;
import it.niedermann.owncloud.notes.shared.model.DBStatus;
import it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType;
import it.niedermann.owncloud.notes.shared.model.IResponseCallback;
import it.niedermann.owncloud.notes.shared.model.ISyncCallback;
import it.niedermann.owncloud.notes.shared.model.NavigationCategory;
import it.niedermann.owncloud.notes.shared.model.SyncResultStatus;
import it.niedermann.owncloud.notes.shared.util.ApiVersionUtil;
import it.niedermann.owncloud.notes.shared.util.NoteUtil;
import it.niedermann.owncloud.notes.shared.util.SSOUtil;

import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.O;
import static androidx.lifecycle.Transformations.distinctUntilChanged;
import static androidx.lifecycle.Transformations.map;
import static it.niedermann.owncloud.notes.edit.EditNoteActivity.ACTION_SHORTCUT;
import static it.niedermann.owncloud.notes.shared.util.NoteUtil.generateNoteExcerpt;
import static it.niedermann.owncloud.notes.widget.notelist.NoteListWidget.updateNoteListWidgets;
import static it.niedermann.owncloud.notes.widget.singlenote.SingleNoteWidget.updateSingleNoteWidgets;
import static java.util.stream.Collectors.toMap;

@SuppressWarnings("UnusedReturnValue")
public class NotesRepository {

    private static final String TAG = NotesRepository.class.getSimpleName();

    private static NotesRepository instance;

    private final ApiProvider apiProvider;
    private final ExecutorService executor;
    private final Context context;
    private final NotesDatabase db;
    private final String defaultNonEmptyTitle;

    /**
     * Track network connection changes using a {@link BroadcastReceiver}
     */
    private boolean isSyncPossible = false;
    private boolean networkConnected = false;
    private String syncOnlyOnWifiKey;
    private boolean syncOnlyOnWifi;
    private final MutableLiveData<Boolean> syncStatus = new MutableLiveData<>(false);
    private final MutableLiveData<ArrayList<Throwable>> syncErrors = new MutableLiveData<>();

    /**
     * @see <a href="https://stackoverflow.com/a/3104265">Do not make this a local variable.</a>
     */
    @SuppressWarnings("FieldCanBeLocal")
    private final SharedPreferences.OnSharedPreferenceChangeListener onSharedPreferenceChangeListener = (SharedPreferences prefs, String key) -> {
        if (syncOnlyOnWifiKey.equals(key)) {
            syncOnlyOnWifi = prefs.getBoolean(syncOnlyOnWifiKey, false);
            updateNetworkStatus();
        }
    };

    private final BroadcastReceiver networkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateNetworkStatus();
            if (isSyncPossible() && SSOUtil.isConfigured(context)) {
                executor.submit(() -> {
                    try {
                        scheduleSync(getAccountByName(SingleAccountHelper.getCurrentSingleSignOnAccount(context).name), false);
                    } catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
                        Log.v(TAG, "Can not select current SingleSignOn account after network changed, do not sync.");
                    }
                });
            }
        }
    };

    // current state of the synchronization
    private final Map<Long, Boolean> syncActive = new HashMap<>();
    private final Map<Long, Boolean> syncScheduled = new HashMap<>();

    // list of callbacks for both parts of synchronization
    private final Map<Long, List<ISyncCallback>> callbacksPush = new HashMap<>();
    private final Map<Long, List<ISyncCallback>> callbacksPull = new HashMap<>();


    public static synchronized NotesRepository getInstance(@NonNull Context context) {
        if (instance == null) {
            instance = new NotesRepository(context, NotesDatabase.getInstance(context.getApplicationContext()), Executors.newCachedThreadPool(), ApiProvider.getInstance());
        }
        return instance;
    }

    private NotesRepository(@NonNull final Context context, @NonNull final NotesDatabase db, @NonNull final ExecutorService executor, @NonNull ApiProvider apiProvider) {
        this.context = context.getApplicationContext();
        this.db = db;
        this.executor = executor;
        this.apiProvider = apiProvider;
        this.defaultNonEmptyTitle = NoteUtil.generateNonEmptyNoteTitle("", this.context);
        this.syncOnlyOnWifiKey = context.getApplicationContext().getResources().getString(R.string.pref_key_wifi_only);

        // Registers BroadcastReceiver to track network connection changes.
        this.context.registerReceiver(networkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
        prefs.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
        syncOnlyOnWifi = prefs.getBoolean(syncOnlyOnWifiKey, false);

        updateNetworkStatus();
    }


    // Accounts

    @AnyThread
    public void addAccount(@NonNull String url, @NonNull String username, @NonNull String accountName, @NonNull Capabilities capabilities, @Nullable String displayName, @NonNull IResponseCallback<Account> callback) {
        final Account createdAccount = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account(url, username, accountName, displayName, capabilities)));
        if (createdAccount == null) {
            callback.onError(new Exception("Could not read created account."));
        } else {
            callback.onSuccess(createdAccount);
        }
    }

    @WorkerThread
    public List<Account> getAccounts() {
        return db.getAccountDao().getAccounts();
    }

    @WorkerThread
    public void deleteAccount(@NonNull Account account) {
        try {
            apiProvider.invalidateAPICache(AccountImporter.getSingleSignOnAccount(context, account.getAccountName()));
        } catch (NextcloudFilesAppAccountNotFoundException e) {
            e.printStackTrace();
            apiProvider.invalidateAPICache();
        }

        db.getAccountDao().deleteAccount(account);
    }

    public Account getAccountByName(String accountName) {
        return db.getAccountDao().getAccountByName(accountName);
    }

    public Account getAccountById(long accountId) {
        return db.getAccountDao().getAccountById(accountId);
    }

    public LiveData<List<Account>> getAccounts$() {
        return db.getAccountDao().getAccounts$();
    }

    public LiveData<Account> getAccountById$(long accountId) {
        return db.getAccountDao().getAccountById$(accountId);
    }

    public LiveData<Integer> countAccounts$() {
        return db.getAccountDao().countAccounts$();
    }

    public void updateBrand(long id, @ColorInt Integer color, @ColorInt Integer textColor) {
        db.getAccountDao().updateBrand(id, color, textColor);
    }

    public void updateETag(long id, String eTag) {
        db.getAccountDao().updateETag(id, eTag);
    }

    public void updateCapabilitiesETag(long id, String capabilitiesETag) {
        db.getAccountDao().updateCapabilitiesETag(id, capabilitiesETag);
    }

    public void updateModified(long id, long modified) {
        db.getAccountDao().updateModified(id, modified);
    }


    // Notes

    public LiveData<Note> getNoteById$(long id) {
        return db.getNoteDao().getNoteById$(id);
    }

    public LiveData<String> getTitle$(long noteId) {
        return distinctUntilChanged(db.getNoteDao().getTitle$(noteId));
    }

    public LiveData<String> getCategory$(long noteId) {
        return distinctUntilChanged(db.getNoteDao().getCategory$(noteId));
    }

    public LiveData<Boolean> isFavorite$(long noteId) {
        return distinctUntilChanged(db.getNoteDao().isFavorite$(noteId));
    }

    public LiveData<Calendar> getModified$(long noteId) {
        return distinctUntilChanged(db.getNoteDao().getModified$(noteId));
    }

    public Note getNoteById(long id) {
        return db.getNoteDao().getNoteById(id);
    }

    public LiveData<Integer> count$(long accountId) {
        return db.getNoteDao().count$(accountId);
    }

    public LiveData<Integer> countFavorites$(long accountId) {
        return db.getNoteDao().countFavorites$(accountId);
    }

    public void updateScrollY(long id, int scrollY) {
        db.getNoteDao().updateScrollY(id, scrollY);
    }

    public LiveData<List<CategoryWithNotesCount>> searchCategories$(Long accountId, String searchTerm) {
        return db.getNoteDao().searchCategories$(accountId, searchTerm);
    }

    public LiveData<List<Note>> searchRecentByModified$(long accountId, String query) {
        return db.getNoteDao().searchRecentByModified$(accountId, query);
    }

    public List<Note> searchRecentByModified(long accountId, String query) {
        return db.getNoteDao().searchRecentByModified(accountId, query);
    }

    public LiveData<List<Note>> searchRecentLexicographically$(long accountId, String query) {
        return db.getNoteDao().searchRecentLexicographically$(accountId, query);
    }

    public LiveData<List<Note>> searchFavoritesByModified$(long accountId, String query) {
        return db.getNoteDao().searchFavoritesByModified$(accountId, query);
    }

    public List<Note> searchFavoritesByModified(long accountId, String query) {
        return db.getNoteDao().searchFavoritesByModified(accountId, query);
    }

    public LiveData<List<Note>> searchFavoritesLexicographically$(long accountId, String query) {
        return db.getNoteDao().searchFavoritesLexicographically$(accountId, query);
    }

    public LiveData<List<Note>> searchUncategorizedByModified$(long accountId, String query) {
        return db.getNoteDao().searchUncategorizedByModified$(accountId, query);
    }

    public List<Note> searchUncategorizedByModified(long accountId, String query) {
        return db.getNoteDao().searchUncategorizedByModified(accountId, query);
    }

    public LiveData<List<Note>> searchUncategorizedLexicographically$(long accountId, String query) {
        return db.getNoteDao().searchUncategorizedLexicographically$(accountId, query);
    }

    public LiveData<List<Note>> searchCategoryByModified$(long accountId, String query, String category) {
        return db.getNoteDao().searchCategoryByModified$(accountId, query, category);
    }

    public List<Note> searchCategoryByModified(long accountId, String query, String category) {
        return db.getNoteDao().searchCategoryByModified(accountId, query, category);
    }

    public LiveData<List<Note>> searchCategoryLexicographically$(long accountId, String query, String category) {
        return db.getNoteDao().searchCategoryLexicographically$(accountId, query, category);
    }

    public LiveData<List<CategoryWithNotesCount>> getCategories$(Long accountId) {
        return db.getNoteDao().getCategories$(accountId);
    }

    public void updateRemoteId(long id, Long remoteId) {
        db.getNoteDao().updateRemoteId(id, remoteId);
    }

    public Long getLocalIdByRemoteId(long accountId, long remoteId) {
        return db.getNoteDao().getLocalIdByRemoteId(accountId, remoteId);
    }

    public List<Note> getLocalModifiedNotes(long accountId) {
        return db.getNoteDao().getLocalModifiedNotes(accountId);
    }

    public void deleteByNoteId(long id, DBStatus forceDBStatus) {
        db.getNoteDao().deleteByNoteId(id, forceDBStatus);
    }

    /**
     * Please note, that db.updateNote() realized an optimistic conflict resolution, which is required for parallel changes of this Note from the UI.
     */
    public int updateIfNotModifiedLocallyDuringSync(long noteId, Long targetModified, String targetTitle, boolean targetFavorite, String targetETag, String targetContent, String targetExcerpt, String contentBeforeSyncStart, String categoryBeforeSyncStart, boolean favoriteBeforeSyncStart) {
        return db.getNoteDao().updateIfNotModifiedLocallyDuringSync(noteId, targetModified, targetTitle, targetFavorite, targetETag, targetContent, targetExcerpt, contentBeforeSyncStart, categoryBeforeSyncStart, favoriteBeforeSyncStart);
    }

    public int updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(long id, Long modified, String title, boolean favorite, String category, String eTag, String content, String excerpt) {
        return db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(id, modified, title, favorite, category, eTag, content, excerpt);
    }

    public long countUnsynchronizedNotes(long accountId) {
        final Long unsynchronizedNotesCount = db.getNoteDao().countUnsynchronizedNotes(accountId);
        return unsynchronizedNotesCount == null ? 0 : unsynchronizedNotesCount;
    }


    // SingleNoteWidget

    public void createOrUpdateSingleNoteWidgetData(SingleNoteWidgetData data) {
        db.getWidgetSingleNoteDao().createOrUpdateSingleNoteWidgetData(data);
    }

    public void removeSingleNoteWidget(int id) {
        db.getWidgetSingleNoteDao().removeSingleNoteWidget(id);
    }

    public SingleNoteWidgetData getSingleNoteWidgetData(int id) {
        return db.getWidgetSingleNoteDao().getSingleNoteWidgetData(id);
    }


    // ListWidget

    public void createOrUpdateNoteListWidgetData(NotesListWidgetData data) {
        db.getWidgetNotesListDao().createOrUpdateNoteListWidgetData(data);
    }

    public void removeNoteListWidget(int appWidgetId) {
        db.getWidgetNotesListDao().removeNoteListWidget(appWidgetId);
    }

    public NotesListWidgetData getNoteListWidgetData(int appWidgetId) {
        return db.getWidgetNotesListDao().getNoteListWidgetData(appWidgetId);
    }

    /**
     * Creates a new Note in the Database and adds a Synchronization Flag.
     *
     * @param note Note
     */
    @NonNull
    @MainThread
    public LiveData<Note> addNoteAndSync(Account account, Note note) {
        final Note entity = new Note(0, null, note.getModified(), note.getTitle(), note.getContent(), note.getCategory(), note.getFavorite(), note.getETag(), DBStatus.LOCAL_EDITED, account.getId(), generateNoteExcerpt(note.getContent(), note.getTitle()), 0);
        final MutableLiveData<Note> ret = new MutableLiveData<>();
        executor.submit(() -> ret.postValue(addNote(account.getId(), entity)));
        return map(ret, newNote -> {
            notifyWidgets();
            scheduleSync(account, true);
            return newNote;
        });
    }

    /**
     * Inserts a note directly into the Database.
     * Excerpt will be generated, {@link DBStatus#LOCAL_EDITED} will be applied in case the note has
     * already has a local ID, otherwise {@link DBStatus#VOID} will be applied.
     * No Synchronisation will be triggered! Use {@link #addNoteAndSync(Account, Note)}!
     *
     * @param note {@link Note} to be added.
     */
    @NonNull
    @WorkerThread
    public Note addNote(long accountId, @NonNull Note note) {
        note.setStatus(note.getId() > 0 ? DBStatus.LOCAL_EDITED : DBStatus.VOID);
        note.setAccountId(accountId);
        note.setExcerpt(generateNoteExcerpt(note.getContent(), note.getTitle()));
        return db.getNoteDao().getNoteById(db.getNoteDao().addNote(note));
    }

    @MainThread
    public LiveData<Note> moveNoteToAnotherAccount(Account account, @NonNull Note note) {
        final Note fullNote = new Note(null, note.getModified(), note.getTitle(), note.getContent(), note.getCategory(), note.getFavorite(), null);
        deleteNoteAndSync(account, note.getId());
        return map(addNoteAndSync(account, fullNote), (createdNote) -> {
            db.getNoteDao().updateStatus(createdNote.getId(), DBStatus.LOCAL_EDITED);
            createdNote.setStatus(DBStatus.LOCAL_EDITED);
            return createdNote;
        });
    }

    /**
     * @return a {@link Map} of remote IDs as keys and local IDs as values of all {@link Note}s of
     * the given {@param accountId} which are not {@link DBStatus#LOCAL_DELETED}
     */
    @NonNull
    @WorkerThread
    public Map<Long, Long> getIdMap(long accountId) {
        return db.getNoteDao()
                .getRemoteIdAndId(accountId)
                .stream()
                .collect(toMap(Note::getRemoteId, Note::getId));
    }

    @AnyThread
    public void toggleFavoriteAndSync(Account account, long noteId) {
        executor.submit(() -> {
            db.getNoteDao().toggleFavorite(noteId);
            scheduleSync(account, true);
        });
    }

    /**
     * Set the category for a given note.
     * This method will search in the database to find out the category id in the db.
     * If there is no such category existing, this method will create it and search again.
     *
     * @param account  The single sign on account
     * @param noteId   The note which will be updated
     * @param category The category title which should be used to find the category id.
     */
    @AnyThread
    public void setCategory(@NonNull Account account, long noteId, @NonNull String category) {
        executor.submit(() -> {
            db.getNoteDao().updateStatus(noteId, DBStatus.LOCAL_EDITED);
            db.getNoteDao().updateCategory(noteId, category);
            scheduleSync(account, true);
        });
    }

    @AnyThread
    public void setTitle(@NonNull Account account, long noteId, @NonNull String title) {
        executor.submit(() -> {
            final Note note = getNoteById(noteId);
            updateNoteAndSync(account, note, note.getContent(), title, null);
        });
    }

    /**
     * Updates a single Note with a new content.
     * The title is derived from the new content automatically, and modified date as well as DBStatus are updated, too -- if the content differs to the state in the database.
     *
     * @param oldNote    Note to be changed
     * @param newContent New content. If this is <code>null</code>, then <code>oldNote</code> is saved again (useful for undoing changes).
     * @param newTitle   New title. If this is <code>null</code>, then either the old title is reused (in case the note has been synced before) or a title is generated (in case it is a new note)
     * @param callback   When the synchronization is finished, this callback will be invoked (optional).
     * @return changed {@link Note} if differs from database, otherwise the old {@link Note}.
     */
    @WorkerThread
    public Note updateNoteAndSync(@NonNull Account localAccount, @NonNull Note oldNote, @Nullable String newContent, @Nullable String newTitle, @Nullable ISyncCallback callback) {
        final Note newNote;
        // Re-read the up to date remoteId from the database because the UI might not have the state after synchronization yet
        // https://github.com/stefan-niedermann/nextcloud-notes/issues/1198
        @Nullable final Long remoteId = db.getNoteDao().getRemoteId(oldNote.getId());
        if (newContent == null) {
            newNote = new Note(oldNote.getId(), remoteId, oldNote.getModified(), oldNote.getTitle(), oldNote.getContent(), oldNote.getCategory(), oldNote.getFavorite(), oldNote.getETag(), DBStatus.LOCAL_EDITED, localAccount.getId(), oldNote.getExcerpt(), oldNote.getScrollY());
        } else {
            final String title;
            if (newTitle != null) {
                title = newTitle;
            } else {
                final ApiVersion preferredApiVersion = ApiVersionUtil.getPreferredApiVersion(localAccount.getApiVersion());
                if ((remoteId == null || preferredApiVersion == null || preferredApiVersion.compareTo(ApiVersion.API_VERSION_1_0) < 0) &&
                        (defaultNonEmptyTitle.equals(oldNote.getTitle()))) {
                    title = NoteUtil.generateNonEmptyNoteTitle(newContent, context);
                } else {
                    title = oldNote.getTitle();
                }
            }
            newNote = new Note(oldNote.getId(), remoteId, Calendar.getInstance(), title, newContent, oldNote.getCategory(), oldNote.getFavorite(), oldNote.getETag(), DBStatus.LOCAL_EDITED, localAccount.getId(), generateNoteExcerpt(newContent, title), oldNote.getScrollY());
        }
        int rows = db.getNoteDao().updateNote(newNote);
        // if data was changed, set new status and schedule sync (with callback); otherwise invoke callback directly.
        if (rows > 0) {
            notifyWidgets();
            if (callback != null) {
                addCallbackPush(localAccount, callback);
            }
            scheduleSync(localAccount, true);
            return newNote;
        } else {
            if (callback != null) {
                callback.onFinish();
            }
            return oldNote;
        }
    }

    /**
     * Marks a Note in the Database as Deleted. In the next Synchronization it will be deleted
     * from the Server.
     *
     * @param id long - ID of the Note that should be deleted
     */
    @AnyThread
    public void deleteNoteAndSync(Account account, long id) {
        executor.submit(() -> {
            db.getNoteDao().updateStatus(id, DBStatus.LOCAL_DELETED);
            notifyWidgets();
            scheduleSync(account, true);

            if (SDK_INT >= O) {
                ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
                if (shortcutManager != null) {
                    shortcutManager.getPinnedShortcuts().forEach((shortcut) -> {
                        String shortcutId = id + "";
                        if (shortcut.getId().equals(shortcutId)) {
                            Log.v(TAG, "Removing shortcut for " + shortcutId);
                            shortcutManager.disableShortcuts(Collections.singletonList(shortcutId), context.getResources().getString(R.string.note_has_been_deleted));
                        }
                    });
                } else {
                    Log.e(TAG, ShortcutManager.class.getSimpleName() + "is null.");
                }
            }
        });
    }

    /**
     * Notify about changed notes.
     */
    @AnyThread
    private void notifyWidgets() {
        executor.submit(() -> {
            updateSingleNoteWidgets(context);
            updateNoteListWidgets(context);
        });
    }

    @AnyThread
    private void updateDynamicShortcuts(long accountId) {
        executor.submit(() -> {
            if (SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
                ShortcutManager shortcutManager = this.context.getSystemService(ShortcutManager.class);
                if (shortcutManager != null) {
                    if (!shortcutManager.isRateLimitingActive()) {
                        List<ShortcutInfo> newShortcuts = new ArrayList<>();

                        for (Note note : db.getNoteDao().getRecentNotes(accountId)) {
                            if (!TextUtils.isEmpty(note.getTitle())) {
                                Intent intent = new Intent(this.context, EditNoteActivity.class);
                                intent.putExtra(EditNoteActivity.PARAM_NOTE_ID, note.getId());
                                intent.setAction(ACTION_SHORTCUT);

                                newShortcuts.add(new ShortcutInfo.Builder(this.context, note.getId() + "")
                                        .setShortLabel(note.getTitle() + "")
                                        .setIcon(Icon.createWithResource(this.context, note.getFavorite() ? R.drawable.ic_star_yellow_24dp : R.drawable.ic_star_grey_ccc_24dp))
                                        .setIntent(intent)
                                        .build());
                            } else {
                                // Prevent crash https://github.com/stefan-niedermann/nextcloud-notes/issues/613
                                Log.e(TAG, "shortLabel cannot be empty " + (BuildConfig.DEBUG ? note : note.getTitle()));
                            }
                        }
                        Log.d(TAG, "Update dynamic shortcuts");
                        shortcutManager.removeAllDynamicShortcuts();
                        shortcutManager.addDynamicShortcuts(newShortcuts);
                    }
                }
            }
        });
    }

    /**
     * @param raw has to be a JSON array as a string <code>["0.2", "1.0", ...]</code>
     */
    public void updateApiVersion(long accountId, @Nullable String raw) {
        final Collection<ApiVersion> apiVersions = ApiVersionUtil.parse(raw);
        if (apiVersions.size() > 0) {
            final int updatedRows = db.getAccountDao().updateApiVersion(accountId, ApiVersionUtil.serialize(apiVersions));
            if (updatedRows == 0) {
                Log.d(TAG, "ApiVersion not updated, because it did not change");
            } else if (updatedRows == 1) {
                Log.i(TAG, "Updated apiVersion to \"" + raw + "\" for accountId = " + accountId);
                apiProvider.invalidateAPICache();
            } else {
                Log.w(TAG, "Updated " + updatedRows + " but expected only 1 for accountId = " + accountId + " and apiVersion = \"" + raw + "\"");
            }
        } else {
            Log.v(TAG, "Could not extract any version from the given String: " + raw);
        }
    }

    /**
     * Modifies the sorting method for one category, the category can be normal category or
     * one of "All notes", "Favorite", and "Uncategorized".
     * If category is one of these three, sorting method will be modified in android.content.SharedPreference.
     * The user can determine use which sorting method to show the notes for a category.
     * When the user changes the sorting method, this method should be called.
     *
     * @param accountId        The user accountID
     * @param selectedCategory The category to be modified
     * @param sortingMethod    The sorting method in {@link CategorySortingMethod} enum format
     */
    @AnyThread
    public void modifyCategoryOrder(long accountId, @NonNull NavigationCategory selectedCategory, @NonNull CategorySortingMethod sortingMethod) {
        executor.submit(() -> {
            final Context ctx = context.getApplicationContext();
            final SharedPreferences.Editor sp = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
            int orderIndex = sortingMethod.getId();

            switch (selectedCategory.getType()) {
                case FAVORITES: {
                    sp.putInt(ctx.getString(R.string.action_sorting_method) + ' ' + ctx.getString(R.string.label_favorites), orderIndex);
                    break;
                }
                case UNCATEGORIZED: {
                    sp.putInt(ctx.getString(R.string.action_sorting_method) + ' ' + ctx.getString(R.string.action_uncategorized), orderIndex);
                    break;
                }
                case RECENT: {
                    sp.putInt(ctx.getString(R.string.action_sorting_method) + ' ' + ctx.getString(R.string.label_all_notes), orderIndex);
                    break;
                }
                case DEFAULT_CATEGORY:
                default: {
                    final String category = selectedCategory.getCategory();
                    if (category != null) {
                        if (db.getCategoryOptionsDao().modifyCategoryOrder(accountId, category, sortingMethod) == 0) {
                            // Nothing updated means we didn't have this yet
                            final CategoryOptions categoryOptions = new CategoryOptions();
                            categoryOptions.setAccountId(accountId);
                            categoryOptions.setCategory(category);
                            categoryOptions.setSortingMethod(sortingMethod);
                            db.getCategoryOptionsDao().addCategoryOptions(categoryOptions);
                        }
                    } else {
                        throw new IllegalStateException("Tried to modify category order for " + ENavigationCategoryType.DEFAULT_CATEGORY + "but category is null.");
                    }
                    break;
                }
            }
            sp.apply();
        });
    }

    /**
     * Gets the sorting method of a {@link NavigationCategory}, the category can be normal
     * {@link CategoryOptions} or one of {@link ENavigationCategoryType}.
     * If the category no normal {@link CategoryOptions}, sorting method will be got from
     * {@link SharedPreferences}.
     * <p>
     * The sorting method of the category can be used to decide to use which sorting method to show
     * the notes for each categories.
     *
     * @param selectedCategory The category
     * @return The sorting method in CategorySortingMethod enum format
     */
    @NonNull
    @MainThread
    public LiveData<CategorySortingMethod> getCategoryOrder(@NonNull NavigationCategory selectedCategory) {
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        String prefKey;

        switch (selectedCategory.getType()) {
            // TODO make this account specific
            case RECENT: {
                prefKey = context.getString(R.string.action_sorting_method) + ' ' + context.getString(R.string.label_all_notes);
                break;
            }
            case FAVORITES: {
                prefKey = context.getString(R.string.action_sorting_method) + ' ' + context.getString(R.string.label_favorites);
                break;
            }
            case UNCATEGORIZED: {
                prefKey = context.getString(R.string.action_sorting_method) + ' ' + context.getString(R.string.action_uncategorized);
                break;
            }
            case DEFAULT_CATEGORY:
            default: {
                final String category = selectedCategory.getCategory();
                if (category != null) {
                    return db.getCategoryOptionsDao().getCategoryOrder(selectedCategory.getAccountId(), category);
                } else {
                    Log.e(TAG, "Cannot read " + CategorySortingMethod.class.getSimpleName() + " for " + ENavigationCategoryType.DEFAULT_CATEGORY + ".");
                    return new MutableLiveData<>(CategorySortingMethod.SORT_MODIFIED_DESC);
                }
            }
        }

        return map(new SharedPreferenceIntLiveData(sp, prefKey, CategorySortingMethod.SORT_MODIFIED_DESC.getId()), CategorySortingMethod::findById);
    }

    @Override
    protected void finalize() throws Throwable {
        this.context.unregisterReceiver(networkReceiver);
        super.finalize();
    }

    /**
     * Synchronization is only possible, if there is an active network connection.
     * <p>
     * This method respects the user preference "Sync on Wi-Fi only".
     * <p>
     * NoteServerSyncHelper observes changes in the network connection.
     * The current state can be retrieved with this method.
     *
     * @return true if sync is possible, otherwise false.
     */
    public boolean isSyncPossible() {
        return isSyncPossible;
    }

    public boolean isNetworkConnected() {
        return networkConnected;
    }

    public boolean isSyncOnlyOnWifi() {
        return syncOnlyOnWifi;
    }

    /**
     * Adds a callback method to the NoteServerSyncHelper for the synchronization part push local changes to the server.
     * All callbacks will be executed once the synchronization operations are done.
     * After execution the callback will be deleted, so it has to be added again if it shall be
     * executed the next time all synchronize operations are finished.
     *
     * @param callback Implementation of ISyncCallback, contains one method that shall be executed.
     */
    private void addCallbackPush(Account account, ISyncCallback callback) {
        if (account == null) {
            Log.i(TAG, "ssoAccount is null. Is this a local account?");
            callback.onScheduled();
            callback.onFinish();
        } else {
            if (!callbacksPush.containsKey(account.getId())) {
                callbacksPush.put(account.getId(), new ArrayList<>());
            }
            Objects.requireNonNull(callbacksPush.get(account.getId())).add(callback);
        }
    }

    /**
     * Adds a callback method to the NoteServerSyncHelper for the synchronization part pull remote changes from the server.
     * All callbacks will be executed once the synchronization operations are done.
     * After execution the callback will be deleted, so it has to be added again if it shall be
     * executed the next time all synchronize operations are finished.
     *
     * @param callback Implementation of ISyncCallback, contains one method that shall be executed.
     */
    public void addCallbackPull(Account account, ISyncCallback callback) {
        if (account == null) {
            Log.i(TAG, "ssoAccount is null. Is this a local account?");
            callback.onScheduled();
            callback.onFinish();
        } else {
            if (!callbacksPull.containsKey(account.getId())) {
                callbacksPull.put(account.getId(), new ArrayList<>());
            }
            Objects.requireNonNull(callbacksPull.get(account.getId())).add(callback);
        }
    }

    /**
     * Schedules a synchronization and start it directly, if the network is connected and no
     * synchronization is currently running.
     *
     * @param onlyLocalChanges Whether to only push local changes to the server or to also load the whole list of notes from the server.
     */
    public synchronized void scheduleSync(@Nullable Account account, boolean onlyLocalChanges) {
        if (account == null) {
            Log.i(TAG, SingleSignOnAccount.class.getSimpleName() + " is null. Is this a local account?");
        } else {
            if (syncActive.get(account.getId()) == null) {
                syncActive.put(account.getId(), false);
            }
            Log.d(TAG, "Sync requested (" + (onlyLocalChanges ? "onlyLocalChanges" : "full") + "; " + (Boolean.TRUE.equals(syncActive.get(account.getId())) ? "sync active" : "sync NOT active") + ") ...");
            if (isSyncPossible() && (!Boolean.TRUE.equals(syncActive.get(account.getId())) || onlyLocalChanges)) {
                syncActive.put(account.getId(), true);
                try {
                    Log.d(TAG, "... starting now");
                    final NotesServerSyncTask syncTask = new NotesServerSyncTask(context, this, account, onlyLocalChanges, apiProvider) {
                        @Override
                        void onPreExecute() {
                            syncStatus.postValue(true);
                            if (!syncScheduled.containsKey(localAccount.getId()) || syncScheduled.get(localAccount.getId()) == null) {
                                syncScheduled.put(localAccount.getId(), false);
                            }
                            if (!onlyLocalChanges && Boolean.TRUE.equals(syncScheduled.get(localAccount.getId()))) {
                                syncScheduled.put(localAccount.getId(), false);
                            }
                        }

                        @Override
                        void onPostExecute(SyncResultStatus status) {
                            for (Throwable e : exceptions) {
                                Log.e(TAG, e.getMessage(), e);
                            }
                            if (!status.pullSuccessful || !status.pushSuccessful) {
                                syncErrors.postValue(exceptions);
                            }
                            syncActive.put(localAccount.getId(), false);
                            // notify callbacks
                            if (callbacks.containsKey(localAccount.getId()) && callbacks.get(localAccount.getId()) != null) {
                                for (ISyncCallback callback : Objects.requireNonNull(callbacks.get(localAccount.getId()))) {
                                    callback.onFinish();
                                }
                            }
                            notifyWidgets();
                            updateDynamicShortcuts(localAccount.getId());
                            // start next sync if scheduled meanwhile
                            if (syncScheduled.containsKey(localAccount.getId()) && syncScheduled.get(localAccount.getId()) != null && Boolean.TRUE.equals(syncScheduled.get(localAccount.getId()))) {
                                scheduleSync(localAccount, false);
                            }
                            syncStatus.postValue(false);
                        }
                    };
                    syncTask.addCallbacks(account, callbacksPush.get(account.getId()));
                    callbacksPush.put(account.getId(), new ArrayList<>());
                    if (!onlyLocalChanges) {
                        syncTask.addCallbacks(account, callbacksPull.get(account.getId()));
                        callbacksPull.put(account.getId(), new ArrayList<>());
                    }
                    executor.submit(syncTask);
                } catch (NextcloudFilesAppAccountNotFoundException e) {
                    Log.e(TAG, "... Could not find " + SingleSignOnAccount.class.getSimpleName() + " for account name " + account.getAccountName());
                    e.printStackTrace();
                }
            } else if (!onlyLocalChanges) {
                Log.d(TAG, "... scheduled");
                syncScheduled.put(account.getId(), true);
                if (callbacksPush.containsKey(account.getId()) && callbacksPush.get(account.getId()) != null) {
                    final List<ISyncCallback> callbacks = callbacksPush.get(account.getId());
                    if (callbacks != null) {
                        for (ISyncCallback callback : callbacks) {
                            callback.onScheduled();
                        }
                    } else {
                        Log.w(TAG, "List of push-callbacks was set for account \"" + account.getAccountName() + "\" but it was null");
                    }
                }
            } else {
                Log.d(TAG, "... do nothing");
                if (callbacksPush.containsKey(account.getId()) && callbacksPush.get(account.getId()) != null) {
                    final List<ISyncCallback> callbacks = callbacksPush.get(account.getId());
                    if (callbacks != null) {
                        for (ISyncCallback callback : callbacks) {
                            callback.onScheduled();
                        }
                    } else {
                        Log.w(TAG, "List of push-callbacks was set for account \"" + account.getAccountName() + "\" but it was null");
                    }
                }
            }
        }
    }

    public void updateNetworkStatus() {
        try {
            final ConnectivityManager connMgr = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connMgr == null) {
                throw new NetworkErrorException("ConnectivityManager is null");
            }

            final NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
            if (activeInfo == null) {
                throw new NetworkErrorException("NetworkInfo is null");
            }

            if (activeInfo.isConnected()) {
                networkConnected = true;

                final NetworkInfo networkInfo = connMgr.getNetworkInfo((ConnectivityManager.TYPE_WIFI));
                if (networkInfo == null) {
                    throw new NetworkErrorException("connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI) is null");
                }

                isSyncPossible = !syncOnlyOnWifi || networkInfo.isConnected();

                if (isSyncPossible) {
                    Log.d(TAG, "Network connection established.");
                } else {
                    Log.d(TAG, "Network connected, but not used because only synced on wifi.");
                }
            } else {
                networkConnected = false;
                isSyncPossible = false;
                Log.d(TAG, "No network connection.");
            }
        } catch (NetworkErrorException e) {
            Log.i(TAG, e.getMessage());
            networkConnected = false;
            isSyncPossible = false;
        }
    }

    @NonNull
    public LiveData<Boolean> getSyncStatus() {
        return distinctUntilChanged(this.syncStatus);
    }

    @NonNull
    public LiveData<ArrayList<Throwable>> getSyncErrors() {
        return this.syncErrors;
    }

    public void updateDisplayName(long id, @Nullable String displayName) {
        db.getAccountDao().updateDisplayName(id, displayName);
    }
}