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

CardDataProvider.java « providers « helpers « remote « deck « nextcloud « niedermann « it « java « main « src « app - github.com/stefan-niedermann/nextcloud-deck.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a1e87897edd2e3bcb00938d787f674b05c59d049 (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
package it.niedermann.nextcloud.deck.remote.helpers.providers;

import android.annotation.SuppressLint;

import com.nextcloud.android.sso.api.EmptyResponse;
import com.nextcloud.android.sso.exceptions.NextcloudHttpRequestFailedException;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import it.niedermann.nextcloud.deck.DeckLog;
import it.niedermann.nextcloud.deck.database.DataBaseAdapter;
import it.niedermann.nextcloud.deck.exceptions.DeckException;
import it.niedermann.nextcloud.deck.exceptions.OfflineException;
import it.niedermann.nextcloud.deck.model.Account;
import it.niedermann.nextcloud.deck.model.Attachment;
import it.niedermann.nextcloud.deck.model.Board;
import it.niedermann.nextcloud.deck.model.Card;
import it.niedermann.nextcloud.deck.model.JoinCardWithLabel;
import it.niedermann.nextcloud.deck.model.JoinCardWithUser;
import it.niedermann.nextcloud.deck.model.Label;
import it.niedermann.nextcloud.deck.model.User;
import it.niedermann.nextcloud.deck.model.enums.DBStatus;
import it.niedermann.nextcloud.deck.model.full.FullCard;
import it.niedermann.nextcloud.deck.model.full.FullStack;
import it.niedermann.nextcloud.deck.model.propagation.CardUpdate;
import it.niedermann.nextcloud.deck.remote.adapters.ServerAdapter;
import it.niedermann.nextcloud.deck.remote.api.ResponseCallback;
import it.niedermann.nextcloud.deck.remote.helpers.SyncHelper;

public class CardDataProvider extends AbstractSyncDataProvider<FullCard> {

    private static final String ALREADY_ARCHIVED_INDICATOR = "Operation not allowed. This card is archived.";
    // see https://github.com/stefan-niedermann/nextcloud-deck/issues/1073
    private static final Set<JoinCardWithLabel> LABEL_JOINS_IN_SYNC = Collections.synchronizedSet(new HashSet<>());
    protected Board board;
    protected FullStack stack;

    public CardDataProvider(AbstractSyncDataProvider<?> parent, Board board, FullStack stack) {
        super(parent);
        this.board = board;
        this.stack = stack;
    }

    @Override
    public void getAllFromServer(ServerAdapter serverAdapter, long accountId, ResponseCallback<List<FullCard>> responder, Instant lastSync) {


        if (stack.getCards() == null || stack.getCards().isEmpty()) {
            responder.onResponse(new ArrayList<>());
            return;
        }
        List<FullCard> result = Collections.synchronizedList(new ArrayList<>());
        for (Card card : stack.getCards()) {
            serverAdapter.getCard(board.getId(), stack.getId(), card.getId(), new ResponseCallback<>(responder.getAccount()) {
                @Override
                public void onResponse(FullCard response) {
                    result.add(response);
                    if (result.size() == stack.getCards().size()) {
                        responder.onResponse(result);
                    }
                }

                @SuppressLint("MissingSuperCall")
                @Override
                public void onError(Throwable throwable) {
                    responder.onError(throwable);
                }
            });
        }
    }

    @Override
    public FullCard getSingleFromDB(DataBaseAdapter dataBaseAdapter, long accountId, FullCard entity) {
        return dataBaseAdapter.getFullCardByRemoteIdDirectly(accountId, entity.getEntity().getId());
    }

    @Override
    public long createInDB(DataBaseAdapter dataBaseAdapter, long accountId, FullCard entity) {
        fixRelations(dataBaseAdapter, accountId, entity);
        return dataBaseAdapter.createCardDirectly(accountId, entity.getCard());
    }

    protected CardUpdate toCardUpdate(FullCard card) {
        CardUpdate c = new CardUpdate(card);
        // FIXME This causes an IndexOutOfBoundsException for the three "Example Tasks" on a fresh Deck server installation
        c.setOwner(card.getOwner().get(0));
        return c;
    }

    protected void fixRelations(DataBaseAdapter dataBaseAdapter, long accountId, FullCard entity) {
        entity.getCard().setStackId(stack.getLocalId());
        if (entity.getOwner() != null && !entity.getOwner().isEmpty()) {
            User user = entity.getOwner().get(0);
            User u = dataBaseAdapter.getUserByUidDirectly(accountId, user.getUid());
            if (u == null) {
                dataBaseAdapter.createUser(accountId, user);
            } else {
                user.setLocalId(u.getLocalId());
                dataBaseAdapter.updateUser(accountId, user, false);
            }
            u = dataBaseAdapter.getUserByUidDirectly(accountId, user.getUid());

            user.setLocalId(u.getLocalId());
            entity.getCard().setUserId(u.getLocalId());
        }
    }


    @Override
    public FullCard applyUpdatesFromRemote(FullCard localEntity, FullCard remoteEntity, Long accountId) {
        if (localEntity.getCard().getUserId() != null) {
            remoteEntity.getCard().setUserId(localEntity.getCard().getUserId());
        }
        return remoteEntity;
    }

    @Override
    public void updateInDB(DataBaseAdapter dataBaseAdapter, long accountId, FullCard entity, boolean setStatus) {
        fixRelations(dataBaseAdapter, accountId, entity);
        dataBaseAdapter.updateCard(entity.getCard(), setStatus);
    }

    @Override
    public void updateInDB(DataBaseAdapter dataBaseAdapter, long accountId, FullCard entity) {
        updateInDB(dataBaseAdapter, accountId, entity, false);
    }

    @Override
    public void goDeeper(SyncHelper syncHelper, FullCard existingEntity, FullCard entityFromServer, ResponseCallback<Boolean> callback) {
        List<Label> labels = entityFromServer.getLabels();
        existingEntity.setLabels(labels);
        List<User> assignedUsers = entityFromServer.getAssignedUsers();
        existingEntity.setAssignedUsers(assignedUsers);
        List<Attachment> attachments = entityFromServer.getAttachments();
        existingEntity.setAttachments(attachments);

        syncHelper.fixRelations(new CardLabelRelationshipProvider(existingEntity.getCard(), existingEntity.getLabels()));
        if (assignedUsers != null && !assignedUsers.isEmpty()) {
            syncHelper.doSyncFor(new UserDataProvider(this, board, stack, existingEntity, existingEntity.getAssignedUsers()));
        }

        syncHelper.fixRelations(new CardUserRelationshipProvider(existingEntity.getCard(), existingEntity.getAssignedUsers()));
        if (attachments == null) {
            attachments = new ArrayList<>();
        }
        syncHelper.doSyncFor(new AttachmentDataProvider(this, board, stack.getStack(), existingEntity, attachments));

        if (callback.getAccount().getServerDeckVersionAsObject().supportsComments()) {
            DeckLog.verbose("Comments - Version is OK, SYNC");
            syncHelper.doSyncFor(new DeckCommentsDataProvider(this, existingEntity.getCard()));
        } else {
            DeckLog.verbose("Comments - Version is too low, DONT SYNC");
        }
        syncHelper.doSyncFor(new OcsProjectDataProvider(this, existingEntity.getCard()));
    }

    @Override
    public void createOnServer(ServerAdapter serverAdapter, DataBaseAdapter dataBaseAdapter, long accountId, ResponseCallback<FullCard> responder, FullCard entity) {
        if (stack.getId() == null) {
            responder.onError(new DeckException(DeckException.Hint.DEPENDENCY_NOT_SYNCED_YET, "Stack \"" +
                    stack.getStack().getTitle() + "\" for Card \"" + entity.getCard().getTitle() +
                    "\" is not synced yet. Perform a full sync (pull to refresh) as soon as you are online again."));
            return;
        }
        entity.getCard().setStackId(stack.getId());
        serverAdapter.createCard(board.getId(), stack.getId(), entity.getCard(), responder);
    }

    @Override
    public void updateOnServer(ServerAdapter serverAdapter, DataBaseAdapter dataBaseAdapter, long accountId, ResponseCallback<FullCard> callback, FullCard entity) {
        CardUpdate update = toCardUpdate(entity);
        update.setStackId(stack.getId());
        // https://github.com/stefan-niedermann/nextcloud-deck/issues/787 resolve archiving-conflict
        serverAdapter.updateCard(board.getId(), stack.getId(), update, new ResponseCallback<>(callback.getAccount()) {
            @Override
            public void onResponse(FullCard response) {
                callback.onResponse(response);
            }

            @SuppressLint("MissingSuperCall")
            @Override
            public void onError(Throwable throwable) {
                if (throwable.getClass() == NextcloudHttpRequestFailedException.class &&
                        throwable.getCause() != null &&
                        throwable.getCause().getClass() == IllegalStateException.class &&
                        throwable.getCause().getMessage() != null &&
                        throwable.getCause().getMessage().contains(ALREADY_ARCHIVED_INDICATOR)) {
                    callback.onResponse(entity);
                } else {
                    callback.onError(throwable);
                }
            }
        });
    }

    @Override
    public void deleteInDB(DataBaseAdapter dataBaseAdapter, long accountId, FullCard fullCard) {
        dataBaseAdapter.deleteCard(fullCard.getCard(), false);
    }

    @Override
    public void deleteOnServer(ServerAdapter serverAdapter, long accountId, ResponseCallback<EmptyResponse> callback, FullCard entity, DataBaseAdapter dataBaseAdapter) {
        serverAdapter.deleteCard(board.getId(), stack.getId(), entity.getCard(), callback);
    }

    @Override
    public List<FullCard> getAllChangedFromDB(DataBaseAdapter dataBaseAdapter, long accountId, Instant lastSync) {
        if (board == null || stack == null) {
            // no cards changed!
            // (see call from StackDataProvider: goDeeperForUpSync called with null for board.)
            // so we can just skip this one and proceed with anything else (users, labels).
            return Collections.emptyList();
        }
        return dataBaseAdapter.getLocallyChangedCardsByLocalStackIdDirectly(accountId, stack.getStack().getLocalId());
    }

    @Override
    public void goDeeperForUpSync(SyncHelper syncHelper, ServerAdapter serverAdapter, DataBaseAdapter dataBaseAdapter, ResponseCallback<Boolean> callback) {
        FullStack stack;
        Board board;
        List<JoinCardWithLabel> changedLabels;
        if (this.stack == null) {
            changedLabels = dataBaseAdapter.getAllChangedLabelJoins();
        } else {
            changedLabels = dataBaseAdapter.getAllChangedLabelJoinsForStack(this.stack.getLocalId());
        }

        Account account = callback.getAccount();
        for (JoinCardWithLabel changedLabelLocal : changedLabels) {
            Card card = dataBaseAdapter.getCardByLocalIdDirectly(account.getId(), changedLabelLocal.getCardId());
            if (card == null) {
                // https://github.com/stefan-niedermann/nextcloud-deck/issues/683#issuecomment-759116820
                continue;
            }
            if (this.stack == null) {
                stack = dataBaseAdapter.getFullStackByLocalIdDirectly(card.getStackId());
            } else {
                stack = this.stack;
            }

            if (this.board == null) {
                board = dataBaseAdapter.getBoardByLocalIdDirectly(stack.getStack().getBoardId());
            } else {
                board = this.board;
            }

            JoinCardWithLabel changedLabel = dataBaseAdapter.getAllChangedLabelJoinsWithRemoteIDs(changedLabelLocal.getCardId(), changedLabelLocal.getLabelId());
            if (changedLabel.getStatusEnum() == DBStatus.LOCAL_DELETED) {
                if (changedLabel.getLabelId() == null || changedLabel.getCardId() == null) {
                    dataBaseAdapter.deleteJoinedLabelForCardPhysicallyByRemoteIDs(account.getId(), changedLabel.getCardId(), changedLabel.getLabelId());
                } else {
                    serverAdapter.unassignLabelFromCard(board.getId(), stack.getId(), changedLabel.getCardId(), changedLabel.getLabelId(), new ResponseCallback<>(account) {
                        @Override
                        public void onResponse(EmptyResponse response) {
                            dataBaseAdapter.deleteJoinedLabelForCardPhysicallyByRemoteIDs(account.getId(), changedLabel.getCardId(), changedLabel.getLabelId());
                        }
                    });
                }
            } else if (changedLabel.getStatusEnum() == DBStatus.LOCAL_EDITED) {
                if (changedLabel.getLabelId() == null || changedLabel.getCardId() == null) {
                    // Sync next time, the card should be available on server then.
                    continue;
                } else {
                    if (!LABEL_JOINS_IN_SYNC.contains(changedLabel)) {
                        // see https://github.com/stefan-niedermann/nextcloud-deck/issues/1073
                        LABEL_JOINS_IN_SYNC.add(changedLabel);
                        serverAdapter.assignLabelToCard(board.getId(), stack.getId(), changedLabel.getCardId(), changedLabel.getLabelId(), new ResponseCallback<>(account) {
                            @Override
                            public void onResponse(EmptyResponse response) {
                                Label label = dataBaseAdapter.getLabelByRemoteIdDirectly(account.getId(), changedLabel.getLabelId());
                                dataBaseAdapter.setStatusForJoinCardWithLabel(card.getLocalId(), label.getLocalId(), DBStatus.UP_TO_DATE.getId());
                                LABEL_JOINS_IN_SYNC.remove(changedLabel);
                            }

                            @Override
                            public void onError(Throwable throwable) {
                                super.onError(throwable);
                                LABEL_JOINS_IN_SYNC.remove(changedLabel);
                            }
                        });
                    }
                }

            }
        }

        List<JoinCardWithUser> changedUsers;
        if (this.stack == null) {
            changedUsers = dataBaseAdapter.getAllChangedUserJoinsWithRemoteIDs();
        } else {
            changedUsers = dataBaseAdapter.getAllChangedUserJoinsWithRemoteIDsForStack(this.stack.getLocalId());
        }
        for (JoinCardWithUser changedUser : changedUsers) {
            // not already known to server?
            if (changedUser.getCardId() == null) {
                //skip for now
                continue;
            }
            Card card = dataBaseAdapter.getCardByRemoteIdDirectly(account.getId(), changedUser.getCardId());

            if (card == null) {
                // weird constellation... see https://github.com/stefan-niedermann/nextcloud-deck/issues/874
                // this shouldn't actually happen, but does as it seems. the card cant be found by remote id (exists!) and account-ID.
                continue;
            }
            if (this.stack == null) {
                stack = dataBaseAdapter.getFullStackByLocalIdDirectly(card.getStackId());
            } else {
                stack = this.stack;
            }

            if (this.board == null) {
                board = dataBaseAdapter.getBoardByLocalIdDirectly(stack.getStack().getBoardId());
            } else {
                board = this.board;
            }
            User user = dataBaseAdapter.getUserByLocalIdDirectly(changedUser.getUserId());
            if (changedUser.getStatusEnum() == DBStatus.LOCAL_DELETED) {
                serverAdapter.unassignUserFromCard(board.getId(), stack.getId(), changedUser.getCardId(), user.getUid(), new ResponseCallback<>(account) {
                    @Override
                    public void onResponse(EmptyResponse response) {
                        dataBaseAdapter.deleteJoinedUserForCardPhysicallyByRemoteIDs(account.getId(), changedUser.getCardId(), user.getUid());
                    }
                });
            } else if (changedUser.getStatusEnum() == DBStatus.LOCAL_EDITED) {
                serverAdapter.assignUserToCard(board.getId(), stack.getId(), changedUser.getCardId(), user.getUid(), new ResponseCallback<>(account) {
                    @Override
                    public void onResponse(EmptyResponse response) {
                        dataBaseAdapter.setStatusForJoinCardWithUser(card.getLocalId(), user.getLocalId(), DBStatus.UP_TO_DATE.getId());
                    }
                });
            }
        }

        List<Attachment> attachments;
        if (this.stack == null) {
            attachments = dataBaseAdapter.getLocallyChangedAttachmentsDirectly(account.getId());
        } else {
            attachments = dataBaseAdapter.getLocallyChangedAttachmentsForStackDirectly(this.stack.getLocalId());
        }
        for (Attachment attachment : attachments) {
            FullCard card = dataBaseAdapter.getFullCardByLocalIdDirectly(account.getId(), attachment.getCardId());
            stack = dataBaseAdapter.getFullStackByLocalIdDirectly(card.getCard().getStackId());
            board = dataBaseAdapter.getBoardByLocalIdDirectly(stack.getStack().getBoardId());
            syncHelper.doUpSyncFor(new AttachmentDataProvider(this, board, stack.getStack(), card, Collections.singletonList(attachment)));
        }

        List<Card> cardsWithChangedComments;
        if (this.stack == null) {
            cardsWithChangedComments = dataBaseAdapter.getCardsWithLocallyChangedCommentsDirectly(account.getId());
        } else {
            cardsWithChangedComments = dataBaseAdapter.getCardsWithLocallyChangedCommentsForStackDirectly(this.stack.getLocalId());
        }
        for (Card card : cardsWithChangedComments) {
            syncHelper.doUpSyncFor(new DeckCommentsDataProvider(this, card));
        }

        callback.onResponse(Boolean.TRUE);
    }

    @Override
    public void handleDeletes(ServerAdapter serverAdapter, DataBaseAdapter dataBaseAdapter, long accountId, List<FullCard> entitiesFromServer) {
        List<FullCard> localCards = dataBaseAdapter.getFullCardsForStackDirectly(accountId, stack.getLocalId(), null);
        List<FullCard> delta = findDelta(entitiesFromServer, localCards);
        for (FullCard cardToDelete : delta) {
            if (cardToDelete.getId() == null) {
                // not pushed up yet so:
                continue;
            }
            if (cardToDelete.getStatus() == DBStatus.LOCAL_MOVED.getId()) {
                //only delete, if the card isn't availible on server anymore.
                serverAdapter.getCard(board.getId(), stack.getId(), cardToDelete.getId(), new ResponseCallback<>(new Account(accountId)) {
                    @Override
                    public void onResponse(FullCard response) {
                        // do not delete, it's still there and was just moved!
                    }

                    @SuppressLint("MissingSuperCall")
                    @Override
                    public void onError(Throwable throwable) {
                        if (!(throwable instanceof OfflineException)) {
                            // most likely permission denied, therefore deleted
                            dataBaseAdapter.deleteCardPhysically(cardToDelete.getCard());
                        }
                    }
                });

                continue;
            }
            dataBaseAdapter.deleteCardPhysically(cardToDelete.getCard());
        }
    }
}