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.MobileLedgerDatabase;
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(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()));
70 if (db.inTransaction()) throw new AssertionError();
72 db.beginTransaction();
75 db.execSQL("update account_values set keep=0;");
76 db.execSQL("update accounts set keep=0;");
79 String last_account_name = null;
81 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
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\":\"([^\"]+)\"");
90 while ((line = buf.readLine()) != null) {
91 Matcher m = account_name_re.matcher(line);
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);
98 addAccount(db, acct_name);
99 publishProgress(++count);
101 last_account_name = acct_name;
106 Matcher tr_m = tr_re.matcher(line);
108 Log.d("account-parser", "<tr> - another account expected");
109 last_account_name = null;
113 if (last_account_name != null) {
114 m = value_re.matcher(line);
115 boolean match_found = false;
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);
124 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
125 new Object[]{last_account_name, currency, Float.valueOf(value)
129 if (match_found) continue;
132 m = descriptions_line_re.matcher(line);
134 db.execSQL("update description_history set keep=0;");
135 m = description_items_re.matcher(line);
137 String description = m.group(1);
138 if (description.isEmpty()) continue;
140 Log.d("db", String.format("Stored description: %s",
142 db.execSQL("insert or replace into description_history"
143 + "(description, description_upper, keep) " + "values(?, ?, 1);",
144 new Object[]{description, description.toUpperCase()
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();
163 } catch (MalformedURLException e) {
164 error = R.string.err_bad_backend_url;
167 catch (FileNotFoundException e) {
168 error = R.string.err_bad_auth;
171 catch (IOException e) {
172 error = R.string.err_net_io_error;
175 catch (Exception e) {
176 error = R.string.err_net_error;
183 private void addAccount(SQLiteDatabase db, String name) {
185 LedgerAccount acc = new LedgerAccount(name);
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);
196 protected void onPostExecute(Void result) {
197 AccountSummary ctx = mContext.get();
198 if (ctx == null) return;
199 ctx.onAccountRefreshDone(this.error);