]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
038515bfb02e4ec32e01293476c179c878276f22
[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.MLDB;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.UUID;
29
30 public final class MobileLedgerProfile {
31     private String uuid;
32     private String name;
33     private String url;
34     private boolean authEnabled;
35     private String authUserName;
36     private String authPassword;
37     public MobileLedgerProfile(String uuid, String name, String url, boolean authEnabled,
38                                String authUserName, String authPassword) {
39         this.uuid = uuid;
40         this.name = name;
41         this.url = url;
42         this.authEnabled = authEnabled;
43         this.authUserName = authUserName;
44         this.authPassword = authPassword;
45     }
46     public MobileLedgerProfile(CharSequence name, CharSequence url, boolean authEnabled,
47                                CharSequence authUserName, CharSequence authPassword) {
48         this.uuid = String.valueOf(UUID.randomUUID());
49         this.name = String.valueOf(name);
50         this.url = String.valueOf(url);
51         this.authEnabled = authEnabled;
52         this.authUserName = String.valueOf(authUserName);
53         this.authPassword = String.valueOf(authPassword);
54     }
55     public static List<MobileLedgerProfile> loadAllFromDB() {
56         List<MobileLedgerProfile> result = new ArrayList<>();
57         SQLiteDatabase db = MLDB.getReadableDatabase();
58         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
59                                          "auth_password FROM profiles", null))
60         {
61             while (cursor.moveToNext()) {
62                 result.add(new MobileLedgerProfile(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getInt(3) == 1, cursor.getString(4),
63                         cursor.getString(5)));
64             }
65         }
66         return result;
67     }
68     public static List<MobileLedgerProfile> createInitialProfileList() {
69         List<MobileLedgerProfile> result = new ArrayList<>();
70         MobileLedgerProfile first =
71                 new MobileLedgerProfile(UUID.randomUUID().toString(), "default", "", false, "", "");
72         first.storeInDB();
73         result.add(first);
74
75         return result;
76     }
77     public static MobileLedgerProfile loadUUIDFromDB(String profileUUID) {
78         SQLiteDatabase db = MLDB.getReadableDatabase();
79         String name;
80         String url;
81         String authUser;
82         String authPassword;
83         Boolean useAuthentication;
84         try (Cursor cursor = db.rawQuery("SELECT name, url, use_authentication, auth_user, " +
85                                          "auth_password FROM profiles WHERE uuid=?",
86                 new String[]{profileUUID}))
87         {
88             if (cursor.moveToNext()) {
89                 name = cursor.getString(0);
90                 url = cursor.getString(1);
91                 useAuthentication = cursor.getInt(2) == 1;
92                 authUser = useAuthentication ? cursor.getString(3) : null;
93                 authPassword = useAuthentication ? cursor.getString(4) : null;
94             }
95             else {
96                 name = "Unknown profile";
97                 url = "Https://server/url";
98                 useAuthentication = false;
99                 authUser = authPassword = null;
100             }
101         }
102
103         return new MobileLedgerProfile(profileUUID, name, url, useAuthentication, authUser,
104                 authPassword);
105     }
106     public String getUuid() {
107         return uuid;
108     }
109     public String getName() {
110         return name;
111     }
112     public void setName(CharSequence text) {
113         setName(String.valueOf(text));
114     }
115     public void setName(String name) {
116         this.name = name;
117     }
118     public String getUrl() {
119         return url;
120     }
121     public void setUrl(CharSequence text) {
122         setUrl(String.valueOf(text));
123     }
124     public void setUrl(String url) {
125         this.url = url;
126     }
127     public boolean isAuthEnabled() {
128         return authEnabled;
129     }
130     public void setAuthEnabled(boolean authEnabled) {
131         this.authEnabled = authEnabled;
132     }
133     public String getAuthUserName() {
134         return authUserName;
135     }
136     public void setAuthUserName(CharSequence text) {
137         setAuthUserName(String.valueOf(text));
138     }
139     public void setAuthUserName(String authUserName) {
140         this.authUserName = authUserName;
141     }
142     public String getAuthPassword() {
143         return authPassword;
144     }
145     public void setAuthPassword(CharSequence text) {
146         setAuthPassword(String.valueOf(text));
147     }
148     public void setAuthPassword(String authPassword) {
149         this.authPassword = authPassword;
150     }
151     public void storeInDB() {
152         SQLiteDatabase db = MLDB.getWritableDatabase();
153         db.beginTransaction();
154         try {
155             db.execSQL("REPLACE INTO profiles(uuid, name, url, use_authentication, auth_user, " +
156                        "auth_password) VALUES(?, ?, ?, ?, ?, ?)",
157                     new Object[]{uuid, name, url, authEnabled, authEnabled ? authUserName : null,
158                                  authEnabled ? authPassword : null
159                     });
160             db.setTransactionSuccessful();
161         }
162         finally {
163             db.endTransaction();
164         }
165     }
166     public void storeAccount(String name) {
167         SQLiteDatabase db = MLDB.getWritableDatabase();
168
169         do {
170             LedgerAccount acc = new LedgerAccount(name);
171             db.execSQL("replace into accounts(profile, name, name_upper, level, keep) values(?, " +
172                        "?, ?, ?, 1)",
173                     new Object[]{this.uuid, name, name.toUpperCase(), acc.getLevel()});
174             name = acc.getParentName();
175         } while (name != null);
176     }
177     public void storeAccountValue(String name, String currency, Float amount) {
178         SQLiteDatabase db = MLDB.getWritableDatabase();
179         db.execSQL("replace into account_values(profile, account, " +
180                    "currency, value, keep) values(?, ?, ?, ?, 1);",
181                 new Object[]{uuid, name, currency, amount});
182     }
183     public void storeTransaction(LedgerTransaction tr) {
184         SQLiteDatabase db = MLDB.getWritableDatabase();
185         tr.fillDataHash();
186         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
187                 new Object[]{uuid, tr.getId()});
188         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
189                 new Object[]{uuid, tr.getId()});
190
191         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
192                    "values(?,?,?,?,?,1)",
193                 new Object[]{uuid, tr.getId(), tr.getDate(), tr.getDescription(), tr.getDataHash()
194                 });
195
196         for (LedgerTransactionAccount item : tr.getAccounts()) {
197             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
198                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
199                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
200                                  item.getCurrency()
201                     });
202         }
203         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
204     }
205     public String get_option_value(String name, String default_value) {
206         SQLiteDatabase db = MLDB.getReadableDatabase();
207         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
208                 new String[]{uuid, name}))
209         {
210             if (cursor.moveToFirst()) {
211                 String result = cursor.getString(0);
212
213                 if (result == null) {
214                     Log.d("profile", "returning default value for " + name);
215                     result = default_value;
216                 }
217                 else Log.d("profile", String.format("option %s=%s", name, result));
218
219                 return result;
220             }
221             else return default_value;
222         }
223         catch (Exception e) {
224             Log.d("db", "returning default value for " + name, e);
225             return default_value;
226         }
227     }
228     public long get_option_value(String name, long default_value) {
229         long longResult;
230         String result = get_option_value(name, "");
231         if ((result == null) || result.isEmpty()) {
232             Log.d("profile", String.format("Returning default value for option %s", name));
233             longResult = default_value;
234         }
235         else {
236             try {
237                 longResult = Long.parseLong(result);
238                 Log.d("profile", String.format("option %s=%s", name, result));
239             }
240             catch (Exception e) {
241                 Log.d("profile", String.format("Returning default value for option %s", name), e);
242                 longResult = default_value;
243             }
244         }
245
246         return longResult;
247     }
248     public void set_option_value(String name, String value) {
249         Log.d("profile", String.format("setting option %s=%s", name, value));
250         SQLiteDatabase db = MLDB.getWritableDatabase();
251         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
252                 new String[]{uuid, name, value});
253     }
254     public void set_option_value(String name, long value) {
255         set_option_value(name, String.valueOf(value));
256     }
257     public void removeFromDB() {
258         SQLiteDatabase db = MLDB.getWritableDatabase();
259         Log.d("db", String.format("removinf progile %s from DB", uuid));
260         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
261     }
262 }