Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

Expand Down Expand Up @@ -81,6 +82,7 @@

import java.net.HttpURLConnection;
import java.util.LinkedList;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -550,7 +552,7 @@ public boolean onQueryTextChange(String newText) {
private void setupNotesList() {
adapter = new ItemAdapter(this, gridView);
listView.setAdapter(adapter);
listView.setItemAnimator(null);
((SimpleItemAnimator) Objects.requireNonNull(listView.getItemAnimator())).setSupportsChangeAnimations(false);
if (gridView) {
final int spanCount = getResources().getInteger(R.integer.grid_view_span_count);
final var gridLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL);
Expand Down Expand Up @@ -909,11 +911,7 @@ public void onNoteFavoriteClick(int position, View view) {
return;
}

final var toggleLiveData = mainViewModel.toggleFavoriteAndSync(note);
toggleLiveData.observe(this, (next) -> {{
toggleLiveData.removeObservers(this);
adapter.notifyItemChanged(position);
}});
mainViewModel.toggleFavoriteAndSync(note);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.card.MaterialCardView;
Expand Down Expand Up @@ -99,10 +100,37 @@ public long getItemId(int position) {
* @param itemList List of items to be set
*/
public void setItemList(@NonNull List<Item> itemList) {
final var oldList = new ArrayList<>(this.itemList);
final var diff = DiffUtil.calculateDiff(new DiffUtil.Callback() {
@Override
public int getOldListSize() {
return oldList.size();
}

@Override
public int getNewListSize() {
return itemList.size();
}

@Override
public boolean areItemsTheSame(int oldPosition, int newPosition) {
final var oldItem = oldList.get(oldPosition);
final var newItem = itemList.get(newPosition);
if (oldItem instanceof Note oldNote && newItem instanceof Note newNote) {
return oldNote.getId() == newNote.getId();
}
return oldItem.equals(newItem);
}

@Override
public boolean areContentsTheSame(int oldPosition, int newPosition) {
return oldList.get(oldPosition).equals(itemList.get(newPosition));
}
});
this.itemList.clear();
this.itemList.addAll(itemList);
this.swipedPosition = null;
notifyDataSetChanged();
diff.dispatchUpdatesTo(this);
}

@NonNull
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ protected void bindModified(@NonNull TextView noteModified, @Nullable Calendar m
}

protected void bindStatus(CircularProgressIndicator noteSyncStatus, DBStatus status, int color) {
noteSyncStatus.setVisibility(DBStatus.VOID.equals(status) ? INVISIBLE : VISIBLE);
noteSyncStatus.setVisibility(DBStatus.VOID.equals(status) || DBStatus.LOCAL_FAVORITED.equals(status) ? INVISIBLE : VISIBLE);

final var context = noteSyncStatus.getContext();
final var util = BrandingUtil.of(color, context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import static androidx.lifecycle.Transformations.map;
import static java.util.stream.Collectors.toMap;
import static it.niedermann.owncloud.notes.edit.EditNoteActivity.ACTION_SHORTCUT;
import static it.niedermann.owncloud.notes.shared.util.ApiVersionUtil.getPreferredApiVersion;
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;
Expand Down Expand Up @@ -48,7 +47,6 @@
import com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException;
import com.nextcloud.android.sso.helper.SingleAccountHelper;
import com.nextcloud.android.sso.model.SingleSignOnAccount;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.shares.OCShare;

import java.util.ArrayList;
Expand Down Expand Up @@ -553,26 +551,8 @@ public Map<Long, Long> getIdMap(long accountId) {
@AnyThread
public void toggleFavoriteAndSync(Account account, Note note) {
executor.submit(() -> {
try {
final var noteWithContent = getNoteById(note.getId());
if (noteWithContent == null) {
return;
}

final var ssoAccount = AccountImporter.getSingleSignOnAccount(context, account.getAccountName());
final var notesAPI = apiProvider.getNotesAPI(context, ssoAccount, getPreferredApiVersion(account.getApiVersion()));
noteWithContent.setFavorite(!noteWithContent.getFavorite());
final var result = notesAPI.updateNote(noteWithContent);
final var response = result.execute();
if (response.isSuccessful()) {
final var updatedNote = response.body();
if (updatedNote != null) {
scheduleSync(account, false);
}
}
} catch (Exception e) {
Log_OC.e(TAG, "toggleFavoriteAndSync: " + e);
}
db.getNoteDao().toggleFavorite(note.getId());
scheduleSync(account, true);
});
}

Expand Down Expand Up @@ -913,7 +893,10 @@ public synchronized void scheduleSync(@Nullable Account account, boolean onlyLoc
final NotesServerSyncTask syncTask = new NotesServerSyncTask(context, this, account, onlyLocalChanges, apiProvider) {
@Override
void onPreExecute() {
syncStatus.postValue(true);
// Local changes are already visible, so no spinner for pushing them
if (!onlyLocalChanges) {
syncStatus.postValue(true);
}
if (!syncScheduled.containsKey(localAccount.getId()) || syncScheduled.get(localAccount.getId()) == null) {
syncScheduled.put(localAccount.getId(), false);
}
Expand Down Expand Up @@ -943,7 +926,9 @@ void onPostExecute(SyncResultStatus status) {
if (syncScheduled.containsKey(localAccount.getId()) && syncScheduled.get(localAccount.getId()) != null && Boolean.TRUE.equals(syncScheduled.get(localAccount.getId()))) {
scheduleSync(localAccount, false);
}
syncStatus.postValue(false);
if (!onlyLocalChanges) {
syncStatus.postValue(false);
}
}
};
syncTask.addCallbacks(account, callbacksPush.get(account.getId()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ private boolean pushLocalChange(@NonNull Note note) {
Log.d(TAG, step + ": " + note.getStatus());
try {
switch (note.getStatus()) {
case LOCAL_EDITED -> pushEditedNote(note);
case LOCAL_EDITED, LOCAL_FAVORITED -> pushEditedNote(note);
case LOCAL_DELETED -> pushDeletedNote(note);
default ->
throw new IllegalStateException("Unknown State of Note " + note + ": " + note.getStatus());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public interface NoteDao {
@Query("SELECT * FROM NOTE WHERE status != 'LOCAL_DELETED' AND accountId = :accountId ORDER BY modified DESC LIMIT 4")
List<Note> getRecentNotes(long accountId);

@Query("UPDATE NOTE SET status = 'LOCAL_EDITED', favorite = ((favorite | 1) - (favorite & 1)) WHERE id = :id")
@Query("UPDATE NOTE SET status = CASE WHEN status = '' THEN 'LOCAL_FAVORITED' ELSE status END, favorite = ((favorite | 1) - (favorite & 1)) WHERE id = :id")
void toggleFavorite(long id);

@Query("UPDATE NOTE SET remoteId = :remoteId WHERE id = :id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,21 +109,6 @@ public Call<Note> createNote(Note note) {
}
}

public Call<Note> updateNote(@NonNull Note note) {
final Long remoteId = note.getRemoteId();
if (remoteId == null) {
return null;
}

if (ApiVersion.API_VERSION_1_0.equals(usedApiVersion)) {
return notesAPI_1_0.updateNote(remoteId, note);
} else if (ApiVersion.API_VERSION_0_2.equals(usedApiVersion)) {
return notesAPI_0_2.updateNote(remoteId, new Note_0_2(note));
} else {
return null;
}
}

public Call<Note> editNote(@NonNull Note note) {
final Long remoteId = note.getRemoteId();
if (remoteId == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,4 @@ public interface NotesAPI_0_2 {

@DELETE("notes/{remoteId}")
Call<EmptyResponse> deleteNote(@Path("remoteId") long noteId);

@PUT("notes/{id}")
Call<Note> updateNote(@Path("id") long id, @Body NotesAPI.Note_0_2 note);
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,4 @@ public interface NotesAPI_1_0 {

@PUT("settings")
Call<NotesSettings> putSettings(@Body NotesSettings settings);

@PUT("notes/{id}")
Call<Note> updateNote(@Path("id") long id, @Body Note note);
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ public enum DBStatus {
*/
LOCAL_EDITED("LOCAL_EDITED"),

/**
* LOCAL_FAVORITED means that only the favorite state of a Note was changed since the last successful synchronization.
* It is synchronized like {@link #LOCAL_EDITED}, but not shown as pending in the UI.
*/
LOCAL_FAVORITED("LOCAL_FAVORITED"),

/**
* LOCAL_DELETED means that the Note was deleted locally, but this information was not yet synchronized.
* Therefore, the Note have to be kept locally until the synchronization has succeeded.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,16 @@ public void toggleFavorite() {
assertTrue(db.getNoteDao().getNoteById(note.getId()).getFavorite());
}

@Test
public void toggleFavoriteStatus() {
db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0));
db.getNoteDao().addNote(new Note(2, 2L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_EDITED, account.getId(), "", 0));
db.getNoteDao().toggleFavorite(1);
db.getNoteDao().toggleFavorite(2);
assertEquals(DBStatus.LOCAL_FAVORITED, db.getNoteDao().getNoteById(1).getStatus());
assertEquals(LOCAL_EDITED, db.getNoteDao().getNoteById(2).getStatus());
}

@Test
public void updateRemoteId() {
final var note = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_DELETED, account.getId(), "", 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
Expand All @@ -63,6 +64,7 @@
import it.niedermann.owncloud.notes.persistence.entity.Note;
import it.niedermann.owncloud.notes.persistence.sync.NotesAPI;
import it.niedermann.owncloud.notes.shared.model.Capabilities;
import it.niedermann.owncloud.notes.shared.model.DBStatus;
import it.niedermann.owncloud.notes.shared.model.IResponseCallback;

@RunWith(RobolectricTestRunner.class)
Expand Down Expand Up @@ -255,6 +257,20 @@ public void moveNoteToAnotherAccount() throws InterruptedException {
verify(repoSpy, times(1)).addNoteAndSync(any(), any());
}

@Test
public void toggleFavoriteAndSync() {
final var repoSpy = spy(repo);
doNothing().when(repoSpy).scheduleSync(any(), anyBoolean());

repoSpy.toggleFavoriteAndSync(account, repoSpy.getNoteById(1));

final var note = repoSpy.getNoteById(1);
assertTrue(note.getFavorite());
assertEquals(DBStatus.LOCAL_FAVORITED, note.getStatus());
assertEquals("C", note.getContent());
verify(repoSpy, times(1)).scheduleSync(account, true);
}

@Test
public void testSyncStatusLiveData() throws InterruptedException, IOException {
NotesTestingUtil.mockSingleSignOn(new SingleSignOnAccount(account.getAccountName(), account.getUserName(), "1337", account.getUrl(), ""));
Expand All @@ -273,7 +289,17 @@ public void testSyncStatusLiveData() throws InterruptedException, IOException {
}

@Test
public void testSyncErrorsLiveData() throws InterruptedException, IOException {
public void testSyncStatusLiveDataIgnoresLocalChanges() throws IOException {
NotesTestingUtil.mockSingleSignOn(new SingleSignOnAccount(account.getAccountName(), account.getUserName(), "1337", account.getUrl(), ""));

final var values = new ArrayList<Boolean>();
repo.getSyncStatus().observeForever(values::add);
repo.scheduleSync(account, true);
assertFalse(values.contains(true));
}

@Test
public void testSyncErrorsLiveData()throws InterruptedException, IOException {
NotesTestingUtil.mockSingleSignOn(new SingleSignOnAccount(account.getAccountName(), account.getUserName(), "1337", account.getUrl(), ""));

assertThrows("The very first time, this LiveData should never have been set", RuntimeException.class, () -> NotesTestingUtil.getOrAwaitValue(repo.getSyncErrors()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static it.niedermann.owncloud.notes.shared.model.DBStatus.LOCAL_EDITED;
import static it.niedermann.owncloud.notes.shared.model.DBStatus.LOCAL_FAVORITED;
import static it.niedermann.owncloud.notes.shared.model.DBStatus.VOID;

import android.content.Context;
Expand Down Expand Up @@ -79,13 +80,15 @@ void onPostExecute(SyncResultStatus status) {
public void testPushLocalChanges() {
when(repo.getLocalModifiedNotes(anyLong())).thenReturn(Arrays.asList(
new Note(1, null, Calendar.getInstance(), "Does not has a remoteId yet, therefore", "This note should be created on the server", "", false, "1", LOCAL_EDITED, 0, "", 0),
new Note(1, 2L, Calendar.getInstance(), "Has already a remoteId, therefore", "This note should be updated on the server", "", false, "1", LOCAL_EDITED, 0, "", 0)
new Note(1, 2L, Calendar.getInstance(), "Has already a remoteId, therefore", "This note should be updated on the server", "", false, "1", LOCAL_EDITED, 0, "", 0),
new Note(1, 3L, Calendar.getInstance(), "Was only favorited, therefore", "This favorite should be updated on the server", "", true, "1", LOCAL_FAVORITED, 0, "", 0)
));

this.task.run();

verify(notesAPI).createNote(argThat(argument -> "This note should be created on the server".equals(argument.getContent())));
verify(notesAPI).editNote(argThat(argument -> "This note should be updated on the server".equals(argument.getContent())));
verify(notesAPI).editNote(argThat(argument -> "This favorite should be updated on the server".equals(argument.getContent())));
}

@Test
Expand Down
Loading