]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
3560831e71945c81bfa12853787693036d119aea
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / profiles / ProfileDetailFragment.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.profiles;
19
20 import android.app.Activity;
21 import android.app.AlertDialog;
22 import android.os.Bundle;
23 import android.text.Editable;
24 import android.text.TextWatcher;
25 import android.view.LayoutInflater;
26 import android.view.Menu;
27 import android.view.MenuInflater;
28 import android.view.MenuItem;
29 import android.view.View;
30 import android.view.ViewGroup;
31 import android.widget.LinearLayout;
32 import android.widget.Switch;
33 import android.widget.TextView;
34
35 import androidx.annotation.NonNull;
36 import androidx.annotation.Nullable;
37 import androidx.fragment.app.Fragment;
38 import androidx.fragment.app.FragmentActivity;
39
40 import com.google.android.material.appbar.CollapsingToolbarLayout;
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
42 import com.google.android.material.textfield.TextInputLayout;
43
44 import net.ktnx.mobileledger.BuildConfig;
45 import net.ktnx.mobileledger.R;
46 import net.ktnx.mobileledger.model.Data;
47 import net.ktnx.mobileledger.model.MobileLedgerProfile;
48 import net.ktnx.mobileledger.ui.HueRingDialog;
49 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
50 import net.ktnx.mobileledger.utils.Colors;
51
52 import org.jetbrains.annotations.NonNls;
53 import org.jetbrains.annotations.NotNull;
54
55 import java.net.MalformedURLException;
56 import java.net.URL;
57 import java.util.ArrayList;
58 import java.util.Objects;
59
60 import static net.ktnx.mobileledger.utils.Logger.debug;
61
62 /**
63  * A fragment representing a single Profile detail screen.
64  * a {@link ProfileDetailActivity}
65  * on handsets.
66  */
67 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
68     /**
69      * The fragment argument representing the item ID that this fragment
70      * represents.
71      */
72     public static final String ARG_ITEM_ID = "item_id";
73     @NonNls
74     private static final String HTTPS_URL_START = "https://";
75
76     /**
77      * The dummy content this fragment is presenting.
78      */
79     private MobileLedgerProfile mProfile;
80     private TextView url;
81     private Switch postingPermitted;
82     private TextInputLayout urlLayout;
83     private LinearLayout authParams;
84     private Switch useAuthentication;
85     private TextView userName;
86     private TextInputLayout userNameLayout;
87     private TextView password;
88     private TextInputLayout passwordLayout;
89     private TextView profileName;
90     private TextInputLayout profileNameLayout;
91     private TextView preferredAccountsFilter;
92     private TextInputLayout preferredAccountsFilterLayout;
93     private View huePickerView;
94     private View insecureWarningText;
95
96     /**
97      * Mandatory empty constructor for the fragment manager to instantiate the
98      * fragment (e.g. upon screen orientation changes).
99      */
100     public ProfileDetailFragment() {
101     }
102     @Override
103     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
104         debug("profiles", "[fragment] Creating profile details options menu");
105         super.onCreateOptionsMenu(menu, inflater);
106         inflater.inflate(R.menu.profile_details, menu);
107         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
108         menuDeleteProfile.setOnMenuItemClickListener(item -> {
109             AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
110             builder.setTitle(mProfile.getName());
111             builder.setMessage(R.string.remove_profile_dialog_message);
112             builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
113                 debug("profiles",
114                         String.format("[fragment] removing profile %s", mProfile.getUuid()));
115                 mProfile.removeFromDB();
116                 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
117                 if (oldList == null) throw new AssertionError();
118                 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
119                 newList.remove(mProfile);
120                 Data.profiles.setValue(newList);
121                 if (mProfile.equals(Data.profile.getValue())) {
122                     debug("profiles", "[fragment] setting current profile to 0");
123                     Data.setCurrentProfile(newList.get(0));
124                 }
125
126                 final FragmentActivity activity = getActivity();
127                 if (activity != null) activity.finish();
128             });
129             builder.show();
130             return false;
131         });
132         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
133         menuDeleteProfile
134                 .setVisible((mProfile != null) && (profiles != null) && (profiles.size() > 1));
135
136         if (BuildConfig.DEBUG) {
137             final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
138             menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
139             menuWipeProfileData.setVisible(mProfile != null);
140         }
141     }
142     private boolean onWipeDataMenuClicked() {
143         // this is a development option, so no confirmation
144         mProfile.wipeAllData();
145         if (mProfile.equals(Data.profile.getValue())) triggerProfileChange();
146         return true;
147     }
148     private void triggerProfileChange() {
149         int index = Data.getProfileIndex(mProfile);
150         MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
151         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
152         if (profiles == null) throw new AssertionError();
153         profiles.set(index, newProfile);
154
155         ProfilesRecyclerViewAdapter prva = ProfilesRecyclerViewAdapter.getInstance();
156         if (prva != null) prva.notifyItemChanged(index);
157
158         if (mProfile.equals(Data.profile.getValue())) Data.profile.setValue(newProfile);
159     }
160     @Override
161     public void onCreate(Bundle savedInstanceState) {
162         super.onCreate(savedInstanceState);
163
164         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
165             int index = getArguments().getInt(ARG_ITEM_ID, -1);
166             ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
167             if ((profiles != null) && (index != -1) && (index < profiles.size()))
168                 mProfile = profiles.get(index);
169
170             Activity activity = this.getActivity();
171             if (activity == null) throw new AssertionError();
172             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
173             if (appBarLayout != null) {
174                 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
175                 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
176             }
177         }
178     }
179     @Override
180     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
181         super.onActivityCreated(savedInstanceState);
182         Activity context = getActivity();
183         if (context == null) return;
184
185         FloatingActionButton fab = context.findViewById(R.id.fab);
186         fab.setOnClickListener(v -> onSaveFabClicked());
187
188         profileName.requestFocus();
189     }
190     private void onSaveFabClicked() {
191         if (!checkValidity()) return;
192
193         if (mProfile != null) {
194             updateProfileFromUI();
195 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
196             mProfile.storeInDB();
197             debug("profiles", "profile stored in DB");
198             triggerProfileChange();
199         }
200         else {
201             mProfile = new MobileLedgerProfile();
202             updateProfileFromUI();
203             mProfile.storeInDB();
204             final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
205             if (profiles == null) throw new AssertionError();
206             ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
207             newList.add(mProfile);
208             Data.profiles.setValue(newList);
209             MobileLedgerProfile.storeProfilesOrder();
210
211             // first profile ever?
212             if (newList.size() == 1) Data.profile.setValue(mProfile);
213         }
214
215         Activity activity = getActivity();
216         if (activity != null) activity.finish();
217     }
218     private void updateProfileFromUI() {
219         mProfile.setName(profileName.getText());
220         mProfile.setUrl(url.getText());
221         mProfile.setPostingPermitted(postingPermitted.isChecked());
222         mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
223         mProfile.setAuthEnabled(useAuthentication.isChecked());
224         mProfile.setAuthUserName(userName.getText());
225         mProfile.setAuthPassword(password.getText());
226         mProfile.setThemeId(huePickerView.getTag());
227     }
228     @Override
229     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
230                              Bundle savedInstanceState) {
231         View rootView = inflater.inflate(R.layout.profile_detail, container, false);
232
233         profileName = rootView.findViewById(R.id.profile_name);
234         profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
235         url = rootView.findViewById(R.id.url);
236         urlLayout = rootView.findViewById(R.id.url_layout);
237         postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
238         authParams = rootView.findViewById(R.id.auth_params);
239         useAuthentication = rootView.findViewById(R.id.enable_http_auth);
240         userName = rootView.findViewById(R.id.auth_user_name);
241         userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
242         password = rootView.findViewById(R.id.password);
243         passwordLayout = rootView.findViewById(R.id.password_layout);
244         huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
245         preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
246         preferredAccountsFilterLayout =
247                 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
248         insecureWarningText = rootView.findViewById(R.id.insecure_scheme_text);
249
250         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
251             debug("profiles", isChecked ? "auth enabled " : "auth disabled");
252             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
253             if (isChecked) userName.requestFocus();
254             checkInsecureSchemeWithAuth();
255         });
256
257         postingPermitted.setOnCheckedChangeListener(
258                 ((buttonView, isChecked) -> preferredAccountsFilterLayout
259                         .setVisibility(isChecked ? View.VISIBLE : View.GONE)));
260
261         hookClearErrorOnFocusListener(profileName, profileNameLayout);
262         hookClearErrorOnFocusListener(url, urlLayout);
263         hookClearErrorOnFocusListener(userName, userNameLayout);
264         hookClearErrorOnFocusListener(password, passwordLayout);
265
266         int profileThemeId;
267         if (mProfile != null) {
268             profileName.setText(mProfile.getName());
269             postingPermitted.setChecked(mProfile.isPostingPermitted());
270             url.setText(mProfile.getUrl());
271             useAuthentication.setChecked(mProfile.isAuthEnabled());
272             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
273             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
274             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
275             preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
276             profileThemeId = mProfile.getThemeId();
277         }
278         else {
279             profileName.setText("");
280             url.setText(HTTPS_URL_START);
281             postingPermitted.setChecked(true);
282             useAuthentication.setChecked(false);
283             authParams.setVisibility(View.GONE);
284             userName.setText("");
285             password.setText("");
286             preferredAccountsFilter.setText(null);
287             profileThemeId = -1;
288         }
289
290         checkInsecureSchemeWithAuth();
291
292         url.addTextChangedListener(new TextWatcher() {
293             @Override
294             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
295
296             }
297             @Override
298             public void onTextChanged(CharSequence s, int start, int before, int count) {
299
300             }
301             @Override
302             public void afterTextChanged(Editable s) {
303                 checkInsecureSchemeWithAuth();
304             }
305         });
306
307         final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
308         final int profileColor = Colors.getPrimaryColorForHue(hue);
309
310         huePickerView.setBackgroundColor(profileColor);
311         huePickerView.setTag(profileThemeId);
312         huePickerView.setOnClickListener(v -> {
313             HueRingDialog d = new HueRingDialog(
314                     Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
315                     (Integer) v.getTag());
316             d.show();
317             d.setColorSelectedListener(this);
318         });
319         return rootView;
320     }
321     private boolean checkUrlValidity() {
322         boolean valid = true;
323
324         String val = String.valueOf(url.getText()).trim();
325         if (val.isEmpty()) {
326             valid = false;
327             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
328         }
329         try {
330             URL url = new URL(val);
331             String host = url.getHost();
332             if (host == null || host.isEmpty()) throw new MalformedURLException("Missing host");
333             String protocol = url.getProtocol().toUpperCase();
334             if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
335                 valid = false;
336                 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
337             }
338         }
339         catch (MalformedURLException e) {
340             valid = false;
341             urlLayout.setError(getResources().getText(R.string.err_invalid_url));
342         }
343
344         return valid;
345     }
346     private void checkInsecureSchemeWithAuth() {
347         boolean showWarning = false;
348
349         if (useAuthentication.isChecked()) {
350             String urlText = url.getText().toString();
351             if (urlText.startsWith("http") && !urlText.startsWith("https")) showWarning = true;
352         }
353
354         if (showWarning) insecureWarningText.setVisibility(View.VISIBLE);
355         else insecureWarningText.setVisibility(View.GONE);
356     }
357     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
358         view.setOnFocusChangeListener((v, hasFocus) -> {
359             if (hasFocus) layout.setError(null);
360         });
361         view.addTextChangedListener(new TextWatcher() {
362             @Override
363             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
364             }
365             @Override
366             public void onTextChanged(CharSequence s, int start, int before, int count) {
367                 layout.setError(null);
368             }
369             @Override
370             public void afterTextChanged(Editable s) {
371             }
372         });
373     }
374     private boolean checkValidity() {
375         boolean valid = true;
376
377         String val = String.valueOf(profileName.getText());
378         if (val.trim().isEmpty()) {
379             valid = false;
380             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
381         }
382
383         if (!checkUrlValidity()) valid = false;
384
385         if (useAuthentication.isChecked()) {
386             val = String.valueOf(userName.getText());
387             if (val.trim().isEmpty()) {
388                 valid = false;
389                 userNameLayout
390                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
391             }
392
393             val = String.valueOf(password.getText());
394             if (val.trim().isEmpty()) {
395                 valid = false;
396                 passwordLayout
397                         .setError(getResources().getText(R.string.err_profile_password_empty));
398             }
399         }
400
401         return valid;
402     }
403     @Override
404     public void onHueSelected(int hue) {
405         huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
406         huePickerView.setTag(hue);
407     }
408 }