]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
profiles: ensure single instance per profile, fix havoc on add/removal of a profile
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of Mobile-Ledger.
4  * Mobile-Ledger 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  * Mobile-Ledger 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 Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
23
24 import net.ktnx.mobileledger.utils.Globals;
25 import net.ktnx.mobileledger.utils.MLDB;
26
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.UUID;
30
31 public final class MobileLedgerProfile {
32     private String uuid;
33     private String name;
34     private String url;
35     private boolean authEnabled;
36     private String authUserName;
37     private String authPassword;
38     public MobileLedgerProfile(String uuid, String name, String url, boolean authEnabled,
39                                String authUserName, String authPassword) {
40         this.uuid = uuid;
41         this.name = name;
42         this.url = url;
43         this.authEnabled = authEnabled;
44         this.authUserName = authUserName;
45         this.authPassword = authPassword;
46     }
47     public MobileLedgerProfile(CharSequence name, CharSequence url, boolean authEnabled,
48                                CharSequence authUserName, CharSequence authPassword) {
49         this.uuid = String.valueOf(UUID.randomUUID());
50         this.name = String.valueOf(name);
51         this.url = String.valueOf(url);
52         this.authEnabled = authEnabled;
53         this.authUserName = String.valueOf(authUserName);
54         this.authPassword = String.valueOf(authPassword);
55     }
56     // loads all profiles into Data.profiles
57     // returns the profile with the given UUID
58     public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
59         MobileLedgerProfile result = null;
60         List<MobileLedgerProfile> list = new ArrayList<>();
61         SQLiteDatabase db = MLDB.getReadableDatabase();
62         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
63                                          "auth_password FROM profiles order by order_no", null))
64         {
65             while (cursor.moveToNext()) {
66                 MobileLedgerProfile item =
67                         new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
68                         cursor.getString(2), cursor.getInt(3) == 1, cursor.getString(4),
69                                 cursor.getString(5));
70                 list.add(item);
71                 if (item.getUuid().equals(currentProfileUUID)) result = item;
72             }
73         }
74         Data.profiles.setList(list);
75         return result;
76     }
77     public static void storeProfilesOrder() {
78         SQLiteDatabase db = MLDB.getWritableDatabase();
79         db.beginTransaction();
80         try {
81             int orderNo = 0;
82             for (MobileLedgerProfile p : Data.profiles.getList()) {
83                 db.execSQL("update profiles set order_no=? where uuid=?",
84                         new Object[]{orderNo, p.getUuid()});
85                 orderNo++;
86             }
87             db.setTransactionSuccessful();
88         }
89         finally {
90             db.endTransaction();
91         }
92     }
93     public static List<MobileLedgerProfile> createInitialProfileList() {
94         List<MobileLedgerProfile> result = new ArrayList<>();
95         MobileLedgerProfile first =
96                 new MobileLedgerProfile(UUID.randomUUID().toString(), "default", "", false, "", "");
97         first.storeInDB();
98         result.add(first);
99
100         return result;
101     }
102     public static MobileLedgerProfile loadUUIDFromDB(String profileUUID) {
103         SQLiteDatabase db = MLDB.getReadableDatabase();
104         String name;
105         String url;
106         String authUser;
107         String authPassword;
108         Boolean useAuthentication;
109         try (Cursor cursor = db.rawQuery("SELECT name, url, use_authentication, auth_user, " +
110                                          "auth_password FROM profiles WHERE uuid=?",
111                 new String[]{profileUUID}))
112         {
113             if (cursor.moveToNext()) {
114                 name = cursor.getString(0);
115                 url = cursor.getString(1);
116                 useAuthentication = cursor.getInt(2) == 1;
117                 authUser = useAuthentication ? cursor.getString(3) : null;
118                 authPassword = useAuthentication ? cursor.getString(4) : null;
119             }
120             else {
121                 name = "Unknown profile";
122                 url = "Https://server/url";
123                 useAuthentication = false;
124                 authUser = authPassword = null;
125             }
126         }
127
128         return new MobileLedgerProfile(profileUUID, name, url, useAuthentication, authUser,
129                 authPassword);
130     }
131     public String getUuid() {
132         return uuid;
133     }
134     public String getName() {
135         return name;
136     }
137     public void setName(String name) {
138         this.name = name;
139     }
140     public void setName(CharSequence text) {
141         setName(String.valueOf(text));
142     }
143     public String getUrl() {
144         return url;
145     }
146     public void setUrl(String url) {
147         this.url = url;
148     }
149     public void setUrl(CharSequence text) {
150         setUrl(String.valueOf(text));
151     }
152     public boolean isAuthEnabled() {
153         return authEnabled;
154     }
155     public void setAuthEnabled(boolean authEnabled) {
156         this.authEnabled = authEnabled;
157     }
158     public String getAuthUserName() {
159         return authUserName;
160     }
161     public void setAuthUserName(String authUserName) {
162         this.authUserName = authUserName;
163     }
164     public void setAuthUserName(CharSequence text) {
165         setAuthUserName(String.valueOf(text));
166     }
167     public String getAuthPassword() {
168         return authPassword;
169     }
170     public void setAuthPassword(String authPassword) {
171         this.authPassword = authPassword;
172     }
173     public void setAuthPassword(CharSequence text) {
174         setAuthPassword(String.valueOf(text));
175     }
176     public void storeInDB() {
177         SQLiteDatabase db = MLDB.getWritableDatabase();
178         db.beginTransaction();
179         try {
180             db.execSQL("REPLACE INTO profiles(uuid, name, url, use_authentication, auth_user, " +
181                        "auth_password) VALUES(?, ?, ?, ?, ?, ?)",
182                     new Object[]{uuid, name, url, authEnabled, authEnabled ? authUserName : null,
183                                  authEnabled ? authPassword : null
184                     });
185             db.setTransactionSuccessful();
186         }
187         finally {
188             db.endTransaction();
189         }
190     }
191     public void storeAccount(LedgerAccount acc) {
192         SQLiteDatabase db = MLDB.getWritableDatabase();
193
194         // replace into is a bad idea because it would reset hidden to its default value
195         // we like the default, but for new accounts only
196         db.execSQL("update accounts set level = ?, keep = 1 where profile=? and name = ?",
197                 new Object[]{acc.getLevel(), uuid, acc.getName()});
198         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level) " +
199                    "select ?,?,?,?,? where (select changes() = 0)",
200                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
201                              acc.getLevel()
202                 });
203     }
204     public void storeAccountValue(String name, String currency, Float amount) {
205         SQLiteDatabase db = MLDB.getWritableDatabase();
206         db.execSQL("replace into account_values(profile, account, " +
207                    "currency, value, keep) values(?, ?, ?, ?, 1);",
208                 new Object[]{uuid, name, currency, amount});
209     }
210     public void storeTransaction(LedgerTransaction tr) {
211         SQLiteDatabase db = MLDB.getWritableDatabase();
212         tr.fillDataHash();
213         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
214                 new Object[]{uuid, tr.getId()});
215         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
216                 new Object[]{uuid, tr.getId()});
217
218         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
219                    "values(?,?,?,?,?,1)",
220                 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
221                              tr.getDescription(), tr.getDataHash()
222                 });
223
224         for (LedgerTransactionAccount item : tr.getAccounts()) {
225             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
226                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
227                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
228                                  item.getCurrency()
229                     });
230         }
231         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
232     }
233     public String getOption(String name, String default_value) {
234         SQLiteDatabase db = MLDB.getReadableDatabase();
235         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
236                 new String[]{uuid, name}))
237         {
238             if (cursor.moveToFirst()) {
239                 String result = cursor.getString(0);
240
241                 if (result == null) {
242                     Log.d("profile", "returning default value for " + name);
243                     result = default_value;
244                 }
245                 else Log.d("profile", String.format("option %s=%s", name, result));
246
247                 return result;
248             }
249             else return default_value;
250         }
251         catch (Exception e) {
252             Log.d("db", "returning default value for " + name, e);
253             return default_value;
254         }
255     }
256     public long getLongOption(String name, long default_value) {
257         long longResult;
258         String result = getOption(name, "");
259         if ((result == null) || result.isEmpty()) {
260             Log.d("profile", String.format("Returning default value for option %s", name));
261             longResult = default_value;
262         }
263         else {
264             try {
265                 longResult = Long.parseLong(result);
266                 Log.d("profile", String.format("option %s=%s", name, result));
267             }
268             catch (Exception e) {
269                 Log.d("profile", String.format("Returning default value for option %s", name), e);
270                 longResult = default_value;
271             }
272         }
273
274         return longResult;
275     }
276     public void setOption(String name, String value) {
277         Log.d("profile", String.format("setting option %s=%s", name, value));
278         SQLiteDatabase db = MLDB.getWritableDatabase();
279         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
280                 new String[]{uuid, name, value});
281     }
282     public void setLongOption(String name, long value) {
283         setOption(name, String.valueOf(value));
284     }
285     public void removeFromDB() {
286         SQLiteDatabase db = MLDB.getWritableDatabase();
287         Log.d("db", String.format("removing progile %s from DB", uuid));
288         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
289     }
290     public LedgerAccount loadAccount(String name) {
291         SQLiteDatabase db = MLDB.getReadableDatabase();
292         try (Cursor cursor = db.rawQuery("SELECT hidden from accounts where profile=? and name=?",
293                 new String[]{uuid, name}))
294         {
295             if (cursor.moveToFirst()) {
296                 LedgerAccount acc = new LedgerAccount(name);
297                 acc.setHidden(cursor.getInt(0) == 1);
298
299                 return acc;
300             }
301         }
302
303         return null;
304     }
305 }