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

DrawerActivity.java « ui « 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: 62068ac3a7b9c2537875f5a96a95e1e58b524942 (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
package it.niedermann.nextcloud.deck.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteConstraintException;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.nextcloud.android.sso.AccountImporter;
import com.nextcloud.android.sso.exceptions.AndroidGetAccountsPermissionNotGranted;
import com.nextcloud.android.sso.exceptions.NextcloudFilesAppNotInstalledException;
import com.nextcloud.android.sso.helper.SingleAccountHelper;
import com.nextcloud.android.sso.model.SingleSignOnAccount;
import com.nextcloud.android.sso.ui.UiExceptionManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindInt;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import it.niedermann.nextcloud.deck.Application;
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.ocs.Capabilities;
import it.niedermann.nextcloud.deck.model.ocs.Version;
import it.niedermann.nextcloud.deck.persistence.sync.SyncManager;
import it.niedermann.nextcloud.deck.persistence.sync.adapters.db.util.WrappedLiveData;
import it.niedermann.nextcloud.deck.ui.board.EditBoardDialogFragment;
import it.niedermann.nextcloud.deck.ui.exception.ExceptionHandler;
import it.niedermann.nextcloud.deck.util.ViewUtil;

public abstract class DrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    protected static final int MENU_ID_ABOUT = -1;
    protected static final int MENU_ID_ADD_BOARD = -2;
    protected static final int MENU_ID_SETTINGS = -3;
    protected static final int MENU_ID_ADD_ACCOUNT = -2;
    protected static final int ACTIVITY_ABOUT = 1;
    protected static final long NO_ACCOUNTS = -1;
    protected static final long NO_BOARDS = -1;
    protected static final long NO_STACKS = -1;

    @BindView(R.id.coordinatorLayout)
    CoordinatorLayout coordinatorLayout;
    @BindView(R.id.navigationView)
    NavigationView navigationView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindString(R.string.account_is_getting_imported)
    String accountIsGettingImported;
    @BindString(R.string.account_already_added)
    String accountAlreadyAdded;
    @BindString(R.string.shared_preference_last_account)
    String sharedPreferenceLastAccount;
    @BindString(R.string.url_fragment_update_deck)
    String urlFragmentUpdateDeck;
    @BindString(R.string.add_board)
    String addBoard;
    @BindString(R.string.no_account)
    String noAccount;
    @BindString(R.string.add_account)
    String addAccount;
    @BindInt(R.integer.minimum_server_app_major)
    int minimumServerAppMajor;
    @BindInt(R.integer.minimum_server_app_minor)
    int minimumServerAppMinor;
    @BindInt(R.integer.minimum_server_app_patch)
    int minimumServerAppPatch;

    protected List<Account> accountsList = new ArrayList<>();
    protected Account account;
    protected boolean accountChooserActive = false;
    protected SyncManager syncManager;
    protected SharedPreferences sharedPreferences;
    private HeaderViewHolder headerViewHolder;
    private Snackbar deckVersionTooLowSnackbar = null;
    private Snackbar accountIsGettingImportedSnackbar;

    private ConnectivityManager.NetworkCallback networkCallback;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AccountImporter.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        AccountImporter.onActivityResult(requestCode, resultCode, data, this, (SingleSignOnAccount account) -> {
            final WrappedLiveData<Account> accountLiveData = this.syncManager.createAccount(new Account(account.name, account.userId, account.url));
            accountLiveData.observe(this, (Account createdAccount) -> {
                if (accountLiveData.hasError()) {
                    try {
                        accountLiveData.throwError();
                    } catch (SQLiteConstraintException ex) {
                        Snackbar.make(coordinatorLayout, accountAlreadyAdded, Snackbar.LENGTH_LONG).show();
                    }
                } else {
                    // Remember last account - THIS HAS TO BE DONE SYNCHRONOUSLY
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    DeckLog.log("--- Write: shared_preference_last_account" + " | " + createdAccount.getId());
                    editor.putLong(sharedPreferenceLastAccount, createdAccount.getId());
                    editor.commit();

                    syncManager.getServerVersion(new IResponseCallback<Capabilities>(createdAccount) {
                        @Override
                        public void onResponse(Capabilities response) {
                            if (response.getDeckVersion().compareTo(new Version(minimumServerAppMajor, minimumServerAppMinor, minimumServerAppPatch)) < 0) {
                                deckVersionTooLowSnackbar = Snackbar.make(coordinatorLayout, R.string.your_deck_version_is_too_old, Snackbar.LENGTH_INDEFINITE).setAction("Learn more", v -> {
                                    new AlertDialog.Builder(DrawerActivity.this, Application.getAppTheme(getApplicationContext()) ? R.style.DialogDarkTheme : R.style.ThemeOverlay_AppCompat_Dialog_Alert)
                                            .setTitle(R.string.update_deck)
                                            .setMessage(R.string.deck_outdated_please_update)
                                            .setPositiveButton(R.string.simple_update, (dialog, whichButton) -> {
                                                Intent openURL = new Intent(Intent.ACTION_VIEW);
                                                openURL.setData(Uri.parse(createdAccount.getUrl() + urlFragmentUpdateDeck));
                                                startActivity(openURL);
                                            })
                                            .setNegativeButton(R.string.simple_discard, null).show();
                                });
                                deckVersionTooLowSnackbar.show();
                                syncManager.deleteAccount(createdAccount.getId());

                                sharedPreferences.getLong(sharedPreferenceLastAccount, NO_ACCOUNTS);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                DeckLog.log("--- Remove: shared_preference_last_account" + " | " + createdAccount.getId());
                                editor.remove(sharedPreferenceLastAccount);
                                editor.commit(); // Has to be done synchronously
                            } else {
                                accountIsGettingImportedSnackbar.show();
                            }
                        }
                    });
                }
            });

            SingleAccountHelper.setCurrentAccount(getApplicationContext(), account.name);
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
        setSupportActionBar(toolbar);

        accountIsGettingImportedSnackbar = Snackbar.make(coordinatorLayout, accountIsGettingImported, Snackbar.LENGTH_INDEFINITE);

        View header = navigationView.getHeaderView(0);
        headerViewHolder = new HeaderViewHolder(header);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        navigationView.setNavigationItemSelectedListener(this);
        syncManager = new SyncManager(this);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        syncManager.hasAccounts().observe(this, (Boolean hasAccounts) -> {
            if (hasAccounts != null && hasAccounts) {
                syncManager.readAccounts().observe(this, (List<Account> accounts) -> {
                    DeckLog.log("+++ readAccounts()");
                    accountsList = accounts;
                    long lastAccountId = sharedPreferences.getLong(sharedPreferenceLastAccount, NO_ACCOUNTS);
                    DeckLog.log("--- Read: shared_preference_last_account" + " | " + lastAccountId);

                    for (Account account : accounts) {
                        if (lastAccountId == account.getId() || lastAccountId == NO_ACCOUNTS) {
                            this.account = account;
                            SingleAccountHelper.setCurrentAccount(getApplicationContext(), this.account.getName());
                            syncManager = new SyncManager(this);
                            setHeaderView();
                            ViewUtil.addAvatar(this, headerViewHolder.currentAccountAvatar, this.account.getUrl(), this.account.getUserName(), R.mipmap.ic_launcher_round);
                            // TODO show spinner
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                registerAutoSyncOnNetworkAvailable();
                            } else {
                                syncManager.synchronize(new IResponseCallback<Boolean>(this.account) {
                                    @Override
                                    public void onResponse(Boolean response) {
                                        accountIsGettingImportedSnackbar.dismiss();
                                    }
                                });
                            }
                            accountSet(this.account);
                            break;
                        }
                    }
                });
            } else {
                showAccountPicker();
            }
        });

        navigationView.getHeaderView(0).findViewById(R.id.drawer_header_view).setOnClickListener(v -> {
            this.accountChooserActive = !this.accountChooserActive;
            if (accountChooserActive) {
                buildSidenavAccountChooser();
            } else {
                buildSidenavMenu();
            }
        });
    }

    private void showAccountPicker() {
        if (deckVersionTooLowSnackbar != null) {
            deckVersionTooLowSnackbar.dismiss();
        }

//        ArrayList<android.accounts.Account> usedAccounts = new ArrayList<>();
//
//        observeOnce(syncManager.readAccounts(), this, (List<Account> accounts) -> {
//            DeckLog.log("+++ readAccounts()");
//
//            for (Account usedAccount : accounts) {
//                usedAccounts.add(AccountImporter.getAccountForName(this, usedAccount.getName()));
//            }

        try {
            AccountImporter.pickNewAccount(this);
        } catch (NextcloudFilesAppNotInstalledException e) {
            UiExceptionManager.showDialogForException(this, e);
            Log.w("Deck", "=============================================================");
            Log.w("Deck", "Nextcloud app is not installed. Cannot choose account");
            e.printStackTrace();
        } catch (AndroidGetAccountsPermissionNotGranted e) {
            AccountImporter.requestAndroidAccountPermissionsAndPickAccount(this);
        }
//        });
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    protected abstract void accountSet(Account account);

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        if (accountChooserActive) {
            switch (item.getItemId()) {
                case MENU_ID_ADD_ACCOUNT:
                    showAccountPicker();
                    break;
                default:
                    this.account = accountsList.get(item.getItemId());
                    SingleAccountHelper.setCurrentAccount(getApplicationContext(), this.account.getName());
                    syncManager = new SyncManager(this);
                    setHeaderView();
                    accountChooserActive = false;
                    accountSet(this.account);

                    // Remember last account
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    DeckLog.log("--- Write: shared_preference_last_account" + " | " + this.account.getId());
                    editor.putLong(sharedPreferenceLastAccount, this.account.getId());
                    editor.apply();
            }
        } else {
            switch (item.getItemId()) {
                case MENU_ID_ABOUT:
                    Intent aboutIntent = new Intent(getApplicationContext(), AboutActivity.class);
                    startActivityForResult(aboutIntent, ACTIVITY_ABOUT);
                    break;
                case MENU_ID_SETTINGS:
                    Intent settingsIntent = new Intent(getApplicationContext(), SettingsActivity.class);
                    startActivityForResult(settingsIntent, ACTIVITY_ABOUT);
                    break;
                case MENU_ID_ADD_BOARD:
                    EditBoardDialogFragment.newInstance().show(getSupportFragmentManager(), addBoard);
                    break;
                default:
                    boardSelected(item.getItemId(), account);
            }
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    protected abstract void boardSelected(int itemId, Account account);

    protected void setHeaderView() {
        ViewUtil.addAvatar(this, navigationView.getHeaderView(0).findViewById(R.id.drawer_current_account), account.getUrl(), account.getUserName(), R.mipmap.ic_launcher_round);
        ((TextView) navigationView.getHeaderView(0).findViewById(R.id.drawer_username_full)).setText(account.getName());
    }

    protected void setNoAccountHeaderView() {
        ViewUtil.addAvatar(this, navigationView.getHeaderView(0).findViewById(R.id.drawer_current_account), null, "", R.mipmap.ic_launcher_round);
        ((TextView) navigationView.getHeaderView(0).findViewById(R.id.drawer_username_full)).setText(noAccount);
    }

    private void buildSidenavAccountChooser() {
        Menu menu = navigationView.getMenu();
        menu.clear();
        if (accountsList == null || accountsList.size() == 0) {
            Objects.requireNonNull(getSupportActionBar()).setTitle(R.string.app_name_short);
            setNoAccountHeaderView();
        } else {
            int index = 0;
            for (Account account : this.accountsList) {
                final int currentIndex = index;
                MenuItem m = menu.add(Menu.NONE, index++, Menu.NONE, account.getName()).setIcon(R.drawable.ic_person_grey600_24dp);
                AppCompatImageButton contextMenu = new AppCompatImageButton(this);
                contextMenu.setBackgroundDrawable(null);

                String uri = account.getUrl() + "/index.php/avatar/" + Uri.encode(account.getUserName()) + "/56";
                Glide.with(this)
                        .load(uri)
                        .apply(RequestOptions.circleCropTransform())
                        .into(new CustomTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                m.setIcon(resource);
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {

                            }
                        });

                contextMenu.setImageDrawable(ViewUtil.getTintedImageView(this, R.drawable.ic_delete_black_24dp, R.color.grey600));
                contextMenu.setOnClickListener((v) -> {
                    if (currentIndex != 0) { // Select first account after deletion
                        this.account = accountsList.get(0);
                        SingleAccountHelper.setCurrentAccount(getApplicationContext(), this.account.getName());
                        syncManager = new SyncManager(this);
                        accountSet(this.account);
                        setHeaderView();
                        accountChooserActive = false;

                        // Remember last account
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        DeckLog.log("--- Write: shared_preference_last_account" + " | " + this.account.getId());
                        editor.putLong(sharedPreferenceLastAccount, this.account.getId());
                        editor.apply();
                    } else if (accountsList.size() > 1) { // Select second account after deletion
                        this.account = accountsList.get(1);
                        SingleAccountHelper.setCurrentAccount(getApplicationContext(), this.account.getName());
                        syncManager = new SyncManager(this);
                        accountSet(this.account);
                        setHeaderView();
                        accountChooserActive = false;

                        // Remember last account
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        DeckLog.log("--- Write: shared_preference_last_account" + " | " + this.account.getId());
                        editor.putLong(sharedPreferenceLastAccount, this.account.getId());
                        editor.apply();
                    } else {
                        accountsList.clear();
                    }

                    syncManager.deleteAccount(account.getId());
                    buildSidenavAccountChooser();
                    drawer.closeDrawer(GravityCompat.START);
                });
                m.setActionView(contextMenu);
            }
        }
        menu.add(Menu.NONE, MENU_ID_ADD_ACCOUNT, Menu.NONE, addAccount).setIcon(R.drawable.ic_person_add_black_24dp);
    }

    abstract void buildSidenavMenu();

    protected static class HeaderViewHolder {
        @BindView(R.id.drawer_current_account)
        ImageView currentAccountAvatar;
        @BindView(R.id.drawer_account_middle)
        ImageView accountMiddleAvatar;
        @BindView(R.id.drawer_account_end)
        ImageView accountEndAvatar;

        @BindView(R.id.drawer_menu_toggle)
        LinearLayout drawerMenuToggle;
        @BindView(R.id.drawer_account_chooser_toggle)
        ImageView drawerMenuToggleIcon;

        HeaderViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void registerAutoSyncOnNetworkAvailable() {
        final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();

        if (connectivityManager != null) {
            if (networkCallback == null) {
                networkCallback = new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(@NonNull Network network) {
                        DeckLog.log("Got Network connection");
                        syncManager.synchronize(new IResponseCallback<Boolean>(account) {
                            @Override
                            public void onResponse(Boolean response) {
                                accountIsGettingImportedSnackbar.dismiss();
                                DeckLog.log("Auto-Sync after connection available successful");
                            }
                        });
                    }

                    @Override
                    public void onLost(@NonNull Network network) {
                        DeckLog.log("Network lost");
                    }
                };
            }
            try {
                connectivityManager.unregisterNetworkCallback(networkCallback);
            } catch (IllegalArgumentException ignored) {
            }
            connectivityManager.registerNetworkCallback(builder.build(), networkCallback);
        }
    }
}