2 * Copyright © 2019 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.annotation.SuppressLint;
21 import android.content.SharedPreferences;
22 import android.database.sqlite.SQLiteDatabase;
23 import android.os.AsyncTask;
24 import android.os.OperationCanceledException;
25 import android.util.Log;
27 import net.ktnx.mobileledger.R;
28 import net.ktnx.mobileledger.model.Data;
29 import net.ktnx.mobileledger.model.LedgerAccount;
30 import net.ktnx.mobileledger.model.LedgerTransaction;
31 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
32 import net.ktnx.mobileledger.ui.activity.MainActivity;
33 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
34 import net.ktnx.mobileledger.utils.MLDB;
35 import net.ktnx.mobileledger.utils.NetworkUtil;
37 import java.io.BufferedReader;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.io.InputStreamReader;
42 import java.lang.ref.WeakReference;
43 import java.net.HttpURLConnection;
44 import java.net.MalformedURLException;
45 import java.net.URLDecoder;
46 import java.util.ArrayList;
47 import java.util.Date;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
52 public class RetrieveTransactionsTask extends
53 AsyncTask<RetrieveTransactionsTask.Params, RetrieveTransactionsTask.Progress, Void> {
54 private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
55 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\\\"]*>([\\d.-]+)</td>");
56 private static final Pattern transactionDescriptionPattern =
57 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
58 private static final Pattern transactionDetailsPattern =
59 Pattern.compile("^\\s+" + "(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
60 private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
61 protected WeakReference<MainActivity> contextRef;
64 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
65 Pattern account_value_re = Pattern.compile(
66 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
67 Pattern tr_end_re = Pattern.compile("</tr>");
68 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
69 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
70 private boolean success;
71 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
72 this.contextRef = contextRef;
74 private static final void L(String msg) {
75 Log.d("transaction-parser", msg);
78 protected void onProgressUpdate(Progress... values) {
79 super.onProgressUpdate(values);
80 MainActivity context = getContext();
81 if (context == null) return;
82 context.onRetrieveProgress(values[0]);
85 protected void onPreExecute() {
87 MainActivity context = getContext();
88 if (context == null) return;
89 context.onRetrieveStart();
92 protected void onPostExecute(Void aVoid) {
93 super.onPostExecute(aVoid);
94 MainActivity context = getContext();
95 if (context == null) return;
96 context.onRetrieveDone(success);
99 protected void onCancelled() {
101 MainActivity context = getContext();
102 if (context == null) return;
103 context.onRetrieveDone(false);
105 @SuppressLint("DefaultLocale")
107 protected Void doInBackground(Params... params) {
108 Progress progress = new Progress();
109 int maxTransactionId = Progress.INDETERMINATE;
111 ArrayList<LedgerAccount> accountList = new ArrayList<>();
112 LedgerAccount lastAccount = null;
113 Data.backgroundTaskCount.incrementAndGet();
115 HttpURLConnection http =
116 NetworkUtil.prepare_connection(params[0].getBackendPref(), "journal");
117 http.setAllowUserInteraction(false);
118 publishProgress(progress);
119 MainActivity ctx = getContext();
120 if (ctx == null) return null;
121 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
122 try (InputStream resp = http.getInputStream()) {
123 if (http.getResponseCode() != 200) throw new IOException(
124 String.format("HTTP error %d", http.getResponseCode()));
125 db.beginTransaction();
127 db.execSQL("UPDATE transactions set keep=0");
128 db.execSQL("update account_values set keep=0;");
129 db.execSQL("update accounts set keep=0;");
131 ParserState state = ParserState.EXPECTING_ACCOUNT;
134 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
136 int processedTransactionCount = 0;
137 int transactionId = 0;
138 int matchedTransactionsCount = 0;
139 LedgerTransaction transaction = null;
141 while ((line = buf.readLine()) != null) {
144 //L(String.format("State is %d", updating));
146 case EXPECTING_ACCOUNT:
147 if (line.equals("<h2>General Journal</h2>")) {
148 state = ParserState.EXPECTING_TRANSACTION;
149 L("→ expecting transaction");
150 Data.accounts.set(accountList);
153 m = account_name_re.matcher(line);
155 String acct_encoded = m.group(1);
156 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
157 acct_name = acct_name.replace("\"", "");
158 L(String.format("found account: %s", acct_name));
160 addAccount(db, acct_name);
161 lastAccount = new LedgerAccount(acct_name);
162 accountList.add(lastAccount);
164 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
165 L("→ expecting account amount");
169 case EXPECTING_ACCOUNT_AMOUNT:
170 m = account_value_re.matcher(line);
171 boolean match_found = false;
176 String value = m.group(1);
177 String currency = m.group(2);
178 if (currency == null) currency = "";
179 value = value.replace(',', '.');
180 L("curr=" + currency + ", value=" + value);
182 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
183 new Object[]{lastAccount.getName(),
187 lastAccount.addAmount(Float.parseFloat(value), currency);
191 state = ParserState.EXPECTING_ACCOUNT;
192 L("→ expecting account");
197 case EXPECTING_TRANSACTION:
198 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
199 m = transactionStartPattern.matcher(line);
201 transactionId = Integer.valueOf(m.group(1));
202 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
204 "found transaction %d → expecting description",
206 progress.setProgress(++processedTransactionCount);
207 if (maxTransactionId < transactionId)
208 maxTransactionId = transactionId;
209 if ((progress.getTotal() == Progress.INDETERMINATE) ||
210 (progress.getTotal() < transactionId))
211 progress.setTotal(transactionId);
212 publishProgress(progress);
214 m = endPattern.matcher(line);
216 L("--- transaction value complete ---");
222 case EXPECTING_TRANSACTION_DESCRIPTION:
223 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
224 m = transactionDescriptionPattern.matcher(line);
226 if (transactionId == 0)
227 throw new TransactionParserException(
228 "Transaction Id is 0 while expecting " +
232 new LedgerTransaction(transactionId, m.group(1),
234 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
235 L(String.format("transaction %d created for %s (%s) →" +
236 " expecting details", transactionId,
237 m.group(1), m.group(2)));
241 case EXPECTING_TRANSACTION_DETAILS:
242 if (line.isEmpty()) {
243 // transaction data collected
244 if (transaction.existsInDb(db)) {
245 db.execSQL("UPDATE transactions SET keep = 1 WHERE id" +
246 "=?", new Integer[]{transaction.getId()});
247 matchedTransactionsCount++;
249 if (matchedTransactionsCount == 100) {
250 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
252 new Integer[]{transaction.getId()});
254 progress.setTotal(progress.getProgress());
255 publishProgress(progress);
260 db.execSQL("DELETE from transactions WHERE id=?",
261 new Integer[]{transaction.getId()});
262 db.execSQL("DELETE from transaction_accounts WHERE " +
264 new Integer[]{transaction.getId()});
265 transaction.insertInto(db);
266 matchedTransactionsCount = 0;
267 progress.setTotal(maxTransactionId);
270 state = ParserState.EXPECTING_TRANSACTION;
272 "transaction %s saved → expecting transaction",
273 transaction.getId()));
275 // sounds like a good idea, but transaction-1 may not be the first one chronologically
276 // for example, when you add the initial seeding transaction after entering some others
277 // if (transactionId == 1) {
278 // L("This was the initial transaction. Terminating " +
284 m = transactionDetailsPattern.matcher(line);
286 String acc_name = m.group(1);
287 String amount = m.group(2);
288 String currency = m.group(3);
289 amount = amount.replace(',', '.');
290 transaction.addAccount(
291 new LedgerTransactionAccount(acc_name,
292 Float.valueOf(amount), currency));
293 L(String.format("%s = %s", acc_name, amount));
295 else throw new IllegalStateException(
296 String.format("Can't parse transaction %d details",
301 throw new RuntimeException(
302 String.format("Unknown parser updating %s", state.name()));
305 if (!isCancelled()) {
306 db.execSQL("DELETE FROM transactions WHERE keep = 0");
307 db.setTransactionSuccessful();
316 if (success && !isCancelled()) {
317 Log.d("db", "Updating transaction value stamp");
318 MLDB.set_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, new Date().getTime());
319 TransactionListViewModel.scheduleTransactionListReload(ctx);
322 catch (MalformedURLException e) {
323 error = R.string.err_bad_backend_url;
326 catch (FileNotFoundException e) {
327 error = R.string.err_bad_auth;
330 catch (IOException e) {
331 error = R.string.err_net_io_error;
335 Data.backgroundTaskCount.decrementAndGet();
339 private MainActivity getContext() {
340 return contextRef.get();
342 private void addAccount(SQLiteDatabase db, String name) {
344 LedgerAccount acc = new LedgerAccount(name);
345 db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
346 new Object[]{acc.getLevel(), name});
347 db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
348 "?,? " + "where (select changes() = 0)",
349 new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
350 name = acc.getParentName();
351 } while (name != null);
353 private void throwIfCancelled() {
354 if (isCancelled()) throw new OperationCanceledException(null);
357 private enum ParserState {
358 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
359 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
362 public static class Params {
363 private SharedPreferences backendPref;
365 public Params(SharedPreferences backendPref) {
366 this.backendPref = backendPref;
368 SharedPreferences getBackendPref() {
373 public class Progress {
374 public static final int INDETERMINATE = -1;
375 private int progress;
378 this(INDETERMINATE, INDETERMINATE);
380 Progress(int progress, int total) {
381 this.progress = progress;
384 public int getProgress() {
387 protected void setProgress(int progress) {
388 this.progress = progress;
390 public int getTotal() {
393 protected void setTotal(int total) {
398 private class TransactionParserException extends IllegalStateException {
399 TransactionParserException(String message) {