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