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;
20 import android.content.SharedPreferences;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
24 import java.io.BufferedReader;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.lang.ref.WeakReference;
30 import java.net.HttpURLConnection;
31 import java.net.MalformedURLException;
32 import java.net.URLDecoder;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
36 class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Void> {
39 private SharedPreferences pref;
40 WeakReference<AccountSummary> mContext;
42 RetrieveAccountsTask(WeakReference<AccountSummary> context) {
47 void setPref(SharedPreferences pref) {
51 protected Void doInBackground(Void... params) {
53 HttpURLConnection http = NetworkUtil.prepare_connection( pref, "add");
54 http.setAllowUserInteraction(false);
55 http.setRequestProperty("Accept-Charset", "UTF-8");
57 try(MobileLedgerDatabase dbh = new MobileLedgerDatabase(mContext.get())) {
58 try(SQLiteDatabase db = dbh.getWritableDatabase()) {
59 try (InputStream resp = http.getInputStream()) {
60 Log.d("update_accounts", String.valueOf(http.getResponseCode()));
61 if (http.getResponseCode() != 200) {
62 throw new IOException(
63 String.format("HTTP error: %d %s", http.getResponseCode(), http.getResponseMessage()));
66 if (db.inTransaction()) throw new AssertionError();
68 db.beginTransaction();
71 db.execSQL("update account_values set keep=0;");
72 db.execSQL("update accounts set keep=0;");
75 String last_account_name = null;
77 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
79 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
80 Pattern value_re = Pattern.compile(
81 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
82 Pattern tr_re = Pattern.compile("</tr>");
83 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
84 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
86 while ((line = buf.readLine()) != null) {
87 Matcher m = account_name_re.matcher(line);
89 String acct_encoded = m.group(1);
90 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
91 acct_name = acct_name.replace("\"", "");
92 Log.d("account-parser", acct_name);
94 addAccount(db, acct_name);
95 publishProgress(++count);
97 last_account_name = acct_name;
102 Matcher tr_m = tr_re.matcher(line);
104 Log.d("account-parser", "<tr> - another account expected");
105 last_account_name = null;
109 if (last_account_name != null) {
110 m = value_re.matcher(line);
111 boolean match_found = false;
114 String value = m.group(1);
115 String currency = m.group(2);
116 if (currency == null) currency = "";
117 value = value.replace(',', '.');
118 Log.d("db", "curr=" + currency + ", value=" + value);
120 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
121 new Object[]{last_account_name, currency, Float.valueOf(value)
125 if (match_found) continue;
128 m = descriptions_line_re.matcher(line);
130 db.execSQL("update description_history set keep=0;");
131 m = description_items_re.matcher(line);
133 String description = m.group(1);
134 if (description.isEmpty()) continue;
136 Log.d("db", String.format("Stored description: %s",
138 db.execSQL("insert or replace into description_history"
139 + "(description, description_upper, keep) " + "values(?, ?, 1);",
140 new Object[]{description, description.toUpperCase()
146 db.execSQL("delete from account_values where keep=0;");
147 db.execSQL("delete from accounts where keep=0;");
148 // db.execSQL("delete from description_history where keep=0;");
149 db.setTransactionSuccessful();
159 } catch (MalformedURLException e) {
160 error = R.string.err_bad_backend_url;
163 catch (FileNotFoundException e) {
164 error = R.string.err_bad_auth;
167 catch (IOException e) {
168 error = R.string.err_net_io_error;
171 catch (Exception e) {
172 error = R.string.err_net_error;
179 private void addAccount(SQLiteDatabase db, String name) {
181 LedgerAccount acc = new LedgerAccount(name);
183 "insert or replace into accounts(name, name_upper, level, parent_name, keep) "
184 + "values(?, ?, ?, ?, 1)",
185 new Object[]{name, name.toUpperCase(), acc.getLevel(), acc.getParentName()});
186 name = acc.getParentName();
187 } while (name != null);
190 protected void onPostExecute(Void result) {
191 AccountSummary ctx = mContext.get();
192 if (ctx == null) return;
193 ctx.onAccountRefreshDone(this.error);