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.
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.
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/>.
18 package net.ktnx.mobileledger.async;
20 import android.content.SharedPreferences;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
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;
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;
42 public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Void> {
45 private SharedPreferences pref;
46 WeakReference<AccountSummary> mContext;
48 public RetrieveAccountsTask(WeakReference<AccountSummary> context) {
53 public void setPref(SharedPreferences pref) {
57 protected Void doInBackground(Void... params) {
59 HttpURLConnection http = NetworkUtil.prepare_connection( pref, "add");
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()));
69 if (db.inTransaction()) throw new AssertionError();
71 db.beginTransaction();
74 db.execSQL("update account_values set keep=0;");
75 db.execSQL("update accounts set keep=0;");
78 String last_account_name = null;
80 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
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\":\"([^\"]+)\"");
89 while ((line = buf.readLine()) != null) {
90 Matcher m = account_name_re.matcher(line);
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);
97 addAccount(db, acct_name);
98 publishProgress(++count);
100 last_account_name = acct_name;
105 Matcher tr_m = tr_re.matcher(line);
107 Log.d("account-parser", "<tr> - another account expected");
108 last_account_name = null;
112 if (last_account_name != null) {
113 m = value_re.matcher(line);
114 boolean match_found = false;
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);
123 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
124 new Object[]{last_account_name, currency, Float.valueOf(value)
128 if (match_found) continue;
131 m = descriptions_line_re.matcher(line);
133 db.execSQL("update description_history set keep=0;");
134 m = description_items_re.matcher(line);
136 String description = m.group(1);
137 if (description.isEmpty()) continue;
139 Log.d("db", String.format("Stored description: %s",
141 db.execSQL("insert or replace into description_history"
142 + "(description, description_upper, keep) " + "values(?, ?, 1);",
143 new Object[]{description, description.toUpperCase()
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();
162 } catch (MalformedURLException e) {
163 error = R.string.err_bad_backend_url;
166 catch (FileNotFoundException e) {
167 error = R.string.err_bad_auth;
170 catch (IOException e) {
171 error = R.string.err_net_io_error;
174 catch (Exception e) {
175 error = R.string.err_net_error;
182 private void addAccount(SQLiteDatabase db, String name) {
184 LedgerAccount acc = new LedgerAccount(name);
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);
195 protected void onPostExecute(Void result) {
196 AccountSummary ctx = mContext.get();
197 if (ctx == null) return;
198 ctx.onAccountRefreshDone(this.error);