]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveAccountsTask.java
forgot to mark the data as loaded -- avoids re-loading it with each display
[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.MobileLedgerDatabase;
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(MobileLedgerDatabase dbh = new MobileLedgerDatabase(mContext.get())) {
62                 try(SQLiteDatabase db = dbh.getWritableDatabase()) {
63                     try (InputStream resp = http.getInputStream()) {
64                         Log.d("update_accounts", String.valueOf(http.getResponseCode()));
65                         if (http.getResponseCode() != 200) {
66                             throw new IOException(
67                                     String.format("HTTP error: %d %s", http.getResponseCode(), http.getResponseMessage()));
68                         }
69                         else {
70                             if (db.inTransaction()) throw new AssertionError();
71
72                             db.beginTransaction();
73
74                             try {
75                                 db.execSQL("update account_values set keep=0;");
76                                 db.execSQL("update accounts set keep=0;");
77
78                                 String line;
79                                 String last_account_name = null;
80                                 BufferedReader buf =
81                                         new BufferedReader(new InputStreamReader(resp, "UTF-8"));
82                                 // %3A is '='
83                                 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
84                                 Pattern value_re = Pattern.compile(
85                                         "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
86                                 Pattern tr_re = Pattern.compile("</tr>");
87                                 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
88                                 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
89                                 int count = 0;
90                                 while ((line = buf.readLine()) != null) {
91                                     Matcher m = account_name_re.matcher(line);
92                                     if (m.find()) {
93                                         String acct_encoded = m.group(1);
94                                         String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
95                                         acct_name = acct_name.replace("\"", "");
96                                         Log.d("account-parser", acct_name);
97
98                                         addAccount(db, acct_name);
99                                         publishProgress(++count);
100
101                                         last_account_name = acct_name;
102
103                                         continue;
104                                     }
105
106                                     Matcher tr_m = tr_re.matcher(line);
107                                     if (tr_m.find()) {
108                                         Log.d("account-parser", "<tr> - another account expected");
109                                         last_account_name = null;
110                                         continue;
111                                     }
112
113                                     if (last_account_name != null) {
114                                         m = value_re.matcher(line);
115                                         boolean match_found = false;
116                                         while (m.find()) {
117                                             match_found = true;
118                                             String value = m.group(1);
119                                             String currency = m.group(2);
120                                             if (currency == null) currency = "";
121                                             value = value.replace(',', '.');
122                                             Log.d("db", "curr=" + currency + ", value=" + value);
123                                             db.execSQL(
124                                                     "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
125                                                     new Object[]{last_account_name, currency, Float.valueOf(value)
126                                                     });
127                                         }
128
129                                         if (match_found) continue;
130                                     }
131
132                                     m = descriptions_line_re.matcher(line);
133                                     if (m.find()) {
134                                         db.execSQL("update description_history set keep=0;");
135                                         m = description_items_re.matcher(line);
136                                         while (m.find()) {
137                                             String description = m.group(1);
138                                             if (description.isEmpty()) continue;
139
140                                             Log.d("db", String.format("Stored description: %s",
141                                                     description));
142                                             db.execSQL("insert or replace into description_history"
143                                                             + "(description, description_upper, keep) " + "values(?, ?, 1);",
144                                                     new Object[]{description, description.toUpperCase()
145                                                     });
146                                         }
147                                     }
148                                 }
149
150                                 db.execSQL("delete from account_values where keep=0;");
151                                 db.execSQL("delete from accounts where keep=0;");
152 //                        db.execSQL("delete from description_history where keep=0;");
153                                 db.setTransactionSuccessful();
154                             }
155                             finally {
156                                 db.endTransaction();
157                             }
158
159                         }
160                     }
161                 }
162             }
163         } catch (MalformedURLException e) {
164             error = R.string.err_bad_backend_url;
165             e.printStackTrace();
166         }
167         catch (FileNotFoundException e) {
168             error = R.string.err_bad_auth;
169             e.printStackTrace();
170         }
171         catch (IOException e) {
172             error = R.string.err_net_io_error;
173             e.printStackTrace();
174         }
175         catch (Exception e) {
176             error = R.string.err_net_error;
177             e.printStackTrace();
178         }
179
180         return null;
181     }
182
183     private void addAccount(SQLiteDatabase db, String name) {
184         do {
185             LedgerAccount acc = new LedgerAccount(name);
186             db.execSQL(
187                     "update accounts set level = ?, keep = 1 where name = ?",
188                     new Object[]{acc.getLevel(), name});
189             db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?,"
190                             + "?,? " + "where (select changes() = 0)",
191                     new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
192             name = acc.getParentName();
193         } while (name != null);
194     }
195     @Override
196     protected void onPostExecute(Void result) {
197         AccountSummary ctx = mContext.get();
198         if (ctx == null) return;
199         ctx.onAccountRefreshDone(this.error);
200     }
201
202 }