]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveAccountsTask.java
move DB stuff into a static class
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveAccountsTask.java
1 /*
2  * Copyright © 2018 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.async;
19
20 import android.content.SharedPreferences;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
23
24 import net.ktnx.mobileledger.AccountSummary;
25 import net.ktnx.mobileledger.R;
26 import net.ktnx.mobileledger.model.LedgerAccount;
27 import net.ktnx.mobileledger.utils.MLDB;
28 import net.ktnx.mobileledger.utils.NetworkUtil;
29
30 import java.io.BufferedReader;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.lang.ref.WeakReference;
36 import java.net.HttpURLConnection;
37 import java.net.MalformedURLException;
38 import java.net.URLDecoder;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41
42 public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Void> {
43     int error;
44
45     private SharedPreferences pref;
46     WeakReference<AccountSummary> mContext;
47
48     public RetrieveAccountsTask(WeakReference<AccountSummary> context) {
49         mContext = context;
50         error = 0;
51     }
52
53     public void setPref(SharedPreferences pref) {
54         this.pref = pref;
55     }
56
57     protected Void doInBackground(Void... params) {
58         try {
59             HttpURLConnection http = NetworkUtil.prepare_connection( pref, "add");
60             publishProgress(0);
61             try (SQLiteDatabase db = MLDB.getDatabase(mContext.get(), MLDB.DatabaseMode.WRITE)) {
62                     try (InputStream resp = http.getInputStream()) {
63                         Log.d("update_accounts", String.valueOf(http.getResponseCode()));
64                         if (http.getResponseCode() != 200) {
65                             throw new IOException(
66                                     String.format("HTTP error: %d %s", http.getResponseCode(), http.getResponseMessage()));
67                         }
68                         else {
69                             if (db.inTransaction()) throw new AssertionError();
70
71                             db.beginTransaction();
72
73                             try {
74                                 db.execSQL("update account_values set keep=0;");
75                                 db.execSQL("update accounts set keep=0;");
76
77                                 String line;
78                                 String last_account_name = null;
79                                 BufferedReader buf =
80                                         new BufferedReader(new InputStreamReader(resp, "UTF-8"));
81                                 // %3A is '='
82                                 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
83                                 Pattern value_re = Pattern.compile(
84                                         "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
85                                 Pattern tr_re = Pattern.compile("</tr>");
86                                 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
87                                 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
88                                 int count = 0;
89                                 while ((line = buf.readLine()) != null) {
90                                     Matcher m = account_name_re.matcher(line);
91                                     if (m.find()) {
92                                         String acct_encoded = m.group(1);
93                                         String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
94                                         acct_name = acct_name.replace("\"", "");
95                                         Log.d("account-parser", acct_name);
96
97                                         addAccount(db, acct_name);
98                                         publishProgress(++count);
99
100                                         last_account_name = acct_name;
101
102                                         continue;
103                                     }
104
105                                     Matcher tr_m = tr_re.matcher(line);
106                                     if (tr_m.find()) {
107                                         Log.d("account-parser", "<tr> - another account expected");
108                                         last_account_name = null;
109                                         continue;
110                                     }
111
112                                     if (last_account_name != null) {
113                                         m = value_re.matcher(line);
114                                         boolean match_found = false;
115                                         while (m.find()) {
116                                             match_found = true;
117                                             String value = m.group(1);
118                                             String currency = m.group(2);
119                                             if (currency == null) currency = "";
120                                             value = value.replace(',', '.');
121                                             Log.d("db", "curr=" + currency + ", value=" + value);
122                                             db.execSQL(
123                                                     "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
124                                                     new Object[]{last_account_name, currency, Float.valueOf(value)
125                                                     });
126                                         }
127
128                                         if (match_found) continue;
129                                     }
130
131                                     m = descriptions_line_re.matcher(line);
132                                     if (m.find()) {
133                                         db.execSQL("update description_history set keep=0;");
134                                         m = description_items_re.matcher(line);
135                                         while (m.find()) {
136                                             String description = m.group(1);
137                                             if (description.isEmpty()) continue;
138
139                                             Log.d("db", String.format("Stored description: %s",
140                                                     description));
141                                             db.execSQL("insert or replace into description_history"
142                                                             + "(description, description_upper, keep) " + "values(?, ?, 1);",
143                                                     new Object[]{description, description.toUpperCase()
144                                                     });
145                                         }
146                                     }
147                                 }
148
149                                 db.execSQL("delete from account_values where keep=0;");
150                                 db.execSQL("delete from accounts where keep=0;");
151 //                        db.execSQL("delete from description_history where keep=0;");
152                                 db.setTransactionSuccessful();
153                             }
154                             finally {
155                                 db.endTransaction();
156                             }
157
158                         }
159                     }
160                 }
161             }
162         } catch (MalformedURLException e) {
163             error = R.string.err_bad_backend_url;
164             e.printStackTrace();
165         }
166         catch (FileNotFoundException e) {
167             error = R.string.err_bad_auth;
168             e.printStackTrace();
169         }
170         catch (IOException e) {
171             error = R.string.err_net_io_error;
172             e.printStackTrace();
173         }
174         catch (Exception e) {
175             error = R.string.err_net_error;
176             e.printStackTrace();
177         }
178
179         return null;
180     }
181
182     private void addAccount(SQLiteDatabase db, String name) {
183         do {
184             LedgerAccount acc = new LedgerAccount(name);
185             db.execSQL(
186                     "update accounts set level = ?, keep = 1 where name = ?",
187                     new Object[]{acc.getLevel(), name});
188             db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?,"
189                             + "?,? " + "where (select changes() = 0)",
190                     new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
191             name = acc.getParentName();
192         } while (name != null);
193     }
194     @Override
195     protected void onPostExecute(Void result) {
196         AccountSummary ctx = mContext.get();
197         if (ctx == null) return;
198         ctx.onAccountRefreshDone(this.error);
199     }
200
201 }