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

SyncManager.java « sync « persistence « 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: 189639068feb8a805469ff21add9a5ee1d98a1ad (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
package it.niedermann.nextcloud.deck.persistence.sync;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import it.niedermann.nextcloud.deck.DeckConsts;
import it.niedermann.nextcloud.deck.DeckLog;
import it.niedermann.nextcloud.deck.R;
import it.niedermann.nextcloud.deck.api.IResponseCallback;
import it.niedermann.nextcloud.deck.model.Account;
import it.niedermann.nextcloud.deck.model.Board;
import it.niedermann.nextcloud.deck.model.Card;
import it.niedermann.nextcloud.deck.model.Label;
import it.niedermann.nextcloud.deck.model.Stack;
import it.niedermann.nextcloud.deck.model.User;
import it.niedermann.nextcloud.deck.model.interfaces.RemoteEntity;
import it.niedermann.nextcloud.deck.persistence.sync.adapters.db.DataBaseAdapter;
import it.niedermann.nextcloud.deck.persistence.sync.adapters.IDataBasePersistenceAdapter;
import it.niedermann.nextcloud.deck.persistence.sync.adapters.db.IDatabaseOnlyAdapter;
import it.niedermann.nextcloud.deck.persistence.sync.adapters.IPersistenceAdapter;
import it.niedermann.nextcloud.deck.persistence.sync.adapters.ServerAdapter;

public class SyncManager implements IDataBasePersistenceAdapter{



    private IDatabaseOnlyAdapter dataBaseAdapter;
    private IPersistenceAdapter serverAdapter;
    private Context applicationContext;
    private Activity sourceActivity;

    public SyncManager(Context applicationContext, Activity sourceActivity){
        this.applicationContext = applicationContext.getApplicationContext();
        this.sourceActivity = sourceActivity;
        dataBaseAdapter = new DataBaseAdapter(this.applicationContext);
        this.serverAdapter =  new ServerAdapter(this.applicationContext, sourceActivity);
    }

    private void doAsync(Runnable r){
        new Thread(r).start();
    }

    public void synchronize(IResponseCallback<Boolean> responseCallback){
        final long accountId = responseCallback.getAccount().getId();
        doAsync(() -> {
            SharedPreferences lastSyncPref = applicationContext.getSharedPreferences(
                    applicationContext.getString(R.string.shared_preference_last_sync), Context.MODE_PRIVATE);
            long lastSync = lastSyncPref.getLong(DeckConsts.LAST_SYNC_KEY, 0L);
            Date lastSyncDate = new Date(lastSync);
            Date now = new Date();

            // welcome to the Call-Pyramid from Hell
            serverAdapter.getBoards(accountId, new IResponseCallback<List<Board>>(responseCallback.getAccount()) {
                @Override
                public void onResponse(List<Board> response) {
                    for (Board b : response) {
                        Board existingBoard = dataBaseAdapter.getBoard(accountId, b.getId());
                        if (existingBoard==null) {
                            dataBaseAdapter.createBoard(accountId, b);
                        } else {
                            dataBaseAdapter.updateBoard(applyUpdatesFromRemote(existingBoard, b, accountId));
                        }
                        synchronizeStacksOf(b, responseCallback);
                    }
                    responseCallback.onResponse(true);
                }

                @Override
                public void onError(Throwable throwable) {
                    responseCallback.onError(throwable);
                }
            });

            //TODO activate when done dev
//                lastSyncPref.edit().putLong(LAST_SYNC_KEY, now.getTime()).apply();
        });
    }

    private void synchronizeStacksOf(final Board board, final IResponseCallback<Boolean> responseCallback) {
        //sync stacks
        Account account = responseCallback.getAccount();
        long accountId = account.getId();
        final Board syncedBoard = dataBaseAdapter.getBoard(accountId, board.getId());
        serverAdapter.getStacks(accountId, board.getId(), new IResponseCallback<List<Stack>>(account) {
            @Override
            public void onResponse(List<Stack> response) {
                for (Stack stack: response) {
                    stack.setBoardId(syncedBoard.getLocalId());
                    Stack existingStack = dataBaseAdapter.getStack(accountId, syncedBoard.getLocalId(), stack.getId());
                    if (existingStack==null) {
                        dataBaseAdapter.createStack(accountId, stack);
                    } else {
                        dataBaseAdapter.updateStack(applyUpdatesFromRemote(existingStack, stack, accountId));
                    }
                    existingStack = dataBaseAdapter.getStack(accountId, syncedBoard.getLocalId(), stack.getId());
                    dataBaseAdapter.deleteJoinedCardsForStack(existingStack.getLocalId());
                    synchronizeCardOf(stack, syncedBoard, responseCallback);
                }
                //responseCallback.onResponse(true);
            }



            @Override
            public void onError(Throwable throwable) {
                responseCallback.onError(throwable);
            }
        });
    }
    private void synchronizeCardOf(final Stack stack, final Board syncedBoard, final IResponseCallback<Boolean> responseCallback) {
        //sync cards
        Account account = responseCallback.getAccount();
        long accountId = account.getId();
        Stack syncedStack = dataBaseAdapter.getStack(accountId, syncedBoard.getLocalId(), stack.getId());

        for (Card c :stack.getCards()){
            DeckLog.log("requesting Card: "+c.getTitle());
            serverAdapter.getCard(accountId, syncedBoard.getId(), syncedStack.getId(), c.getId(), new IResponseCallback<Card>(account) {
                @Override
                public void onResponse(Card card) {

                    List<User> assignedUsers = card.getAssignedUsers();
                    List<Label> labels = card.getLabels();
                    card.setStack(syncedStack);
                    card.setStackId(syncedStack.getLocalId());
                    Card existingCard = dataBaseAdapter.getCard(accountId, card.getId());
                    if (existingCard==null) {
                        DeckLog.log("creating Card...");
                        dataBaseAdapter.createCard(accountId, card);
                    } else {
                        DeckLog.log("updating Card...");
                        dataBaseAdapter.updateCard(applyUpdatesFromRemote(existingCard, card, accountId));
                    }

                    existingCard = dataBaseAdapter.getCard(accountId, card.getId());
                    dataBaseAdapter.createJoinStackWithCard(existingCard.getLocalId(), syncedStack.getLocalId());
                    existingCard.setLabels(new ArrayList<>());
                    existingCard.setAssignedUsers(new ArrayList<>());

                    ArrayList<User> existingUsers = new ArrayList<>();
                    dataBaseAdapter.deleteJoinedUsersForCard(existingCard.getLocalId());
                    for (User user : assignedUsers) {
                        User existingUser = dataBaseAdapter.getUser(accountId, user.getId());
                        if (existingUser == null){
                            DeckLog.log("creating user: "+user.getUid());
                            dataBaseAdapter.createUser(accountId, user);
                            existingUser = dataBaseAdapter.getUser(accountId, user.getId());
                        } else {
                            DeckLog.log("updating user: "+user.getUid());
                            existingUser = applyUpdatesFromRemote(existingUser, user, accountId);
                            dataBaseAdapter.updateUser(accountId, existingUser);
                        }
                        dataBaseAdapter.createJoinCardWithUser(existingUser.getLocalId(), existingCard.getLocalId());
                        existingUsers.add(existingUser);
                    }
                    ArrayList<Label> existingLabels = new ArrayList<>();
                    dataBaseAdapter.deleteJoinedLabelsForCard(existingCard.getLocalId());
                    for (Label label : labels) {
                        Label existingLabel = dataBaseAdapter.getLabel(accountId, label.getId());
                        if (existingLabel == null){
                            DeckLog.log("creating Label: "+label.getTitle());
                            dataBaseAdapter.createLabel(accountId, label);
                        } else {
                            DeckLog.log("updating Label: "+label.getTitle());
                            existingLabel = applyUpdatesFromRemote(existingLabel, label, accountId);
                            dataBaseAdapter.updateLabel(accountId, existingLabel);
                        }
                        dataBaseAdapter.createJoinCardWithLabel(existingLabel.getLocalId(), existingCard.getLocalId());
                        existingLabels.add(existingLabel);
                    }

                    existingCard.setAssignedUsers(existingUsers);
                    existingCard.setLabels(existingLabels);
                    dataBaseAdapter.updateCard(existingCard);
                }

                @Override
                public void onError(Throwable throwable) {
                    responseCallback.onError(throwable);
                }
            });
        }
    }
    private <T> IResponseCallback<T> wrapCallForUi(IResponseCallback<T> responseCallback) {
        Account account = responseCallback.getAccount();
        if (account == null || account.getId() == null){
            throw new IllegalArgumentException("Bro. Please just give me a damn Account!");
        }
        return new IResponseCallback<T>(responseCallback.getAccount()) {
            @Override
            public void onResponse(T response) {
                sourceActivity.runOnUiThread(()->{
                    fillAccountIDs(response);
                    responseCallback.onResponse(response);
                });
            }

            @Override
            public void onError(Throwable throwable) {
                responseCallback.onError(throwable);
            }
        };
    }

    private <T extends RemoteEntity> T applyUpdatesFromRemote(T localEntity, T remoteEntity, Long accountId) {
        if(!localEntity.getId().equals(remoteEntity.getId())
                || !accountId.equals(localEntity.getAccount().getId())) {
            throw new IllegalArgumentException("IDs of Account or Entity are not matching! WTF are you doin?!");
        }
        remoteEntity.setLastModifiedLocal(remoteEntity.getLastModified()); // not an error! local-modification = remote-mod
        remoteEntity.setLocalId(localEntity.getLocalId());
        return remoteEntity;
    }

    public boolean hasAccounts() {
        return dataBaseAdapter.hasAccounts();
    }

    @Override
    public Account createAccount(String accoutName) {
        return dataBaseAdapter.createAccount(accoutName);
    }

    @Override
    public void deleteAccount(long id) {
        dataBaseAdapter.deleteAccount(id);
    }

    @Override
    public void updateAccount(Account account) {
        dataBaseAdapter.updateAccount(account);
    }

    @Override
    public Account readAccount(long id) {
        return dataBaseAdapter.readAccount(id);
    }

    @Override
    public List<Account> readAccounts() {
        return dataBaseAdapter.readAccounts();
    }

    @Override
    public void getBoards(long accountId, IResponseCallback<List<Board>> responseCallback) {
        dataBaseAdapter.getBoards(accountId, wrapCallForUi(responseCallback));
    }

    @Override
    public void createBoard(long accountId, Board board) {
        doAsync(() -> {
            dataBaseAdapter.createBoard(accountId, board);
            serverAdapter.createBoard(accountId, board);
        });
    }

    @Override
    public void deleteBoard(Board board) {

    }

    @Override
    public void updateBoard(Board board) {

    }

    @Override
    public void getStacks(long accountId, long localBoardId, IResponseCallback<List<Stack>> responseCallback) {
        dataBaseAdapter.getStacks(accountId, localBoardId, wrapCallForUi(responseCallback));
    }

    @Override
    public void getStack(long accountId, long localBoardId, long stackId, IResponseCallback<Stack> responseCallback) {
        dataBaseAdapter.getStack(accountId, localBoardId, stackId, wrapCallForUi(responseCallback));
    }

    @Override
    public void createStack(long accountId, Stack stack) {
        dataBaseAdapter.createStack(accountId, stack);
        //TODO implement
    }

    @Override
    public void deleteStack(Stack stack) {

    }

    @Override
    public void updateStack(Stack stack) {

    }

    @Override
    public void getCard(long accountId, long boardId, long stackId, long cardId, IResponseCallback<Card> responseCallback) {
        dataBaseAdapter.getCard(accountId, boardId, stackId, cardId, wrapCallForUi(responseCallback));
    }

    @Override
    public void createCard(long accountId, Card card) {

    }

    @Override
    public void deleteCard(Card card) {

    }

    @Override
    public void updateCard(Card card) {

    }
}