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.annotation.SuppressLint;
21 import android.content.SharedPreferences;
22 import android.database.sqlite.SQLiteDatabase;
23 import android.os.AsyncTask;
24 import android.util.Log;
26 import net.ktnx.mobileledger.R;
27 import net.ktnx.mobileledger.TransactionListActivity;
28 import net.ktnx.mobileledger.model.LedgerTransaction;
29 import net.ktnx.mobileledger.model.LedgerTransactionItem;
30 import net.ktnx.mobileledger.utils.MLDB;
31 import net.ktnx.mobileledger.utils.NetworkUtil;
33 import java.io.BufferedReader;
34 import java.io.FileNotFoundException;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.lang.ref.WeakReference;
39 import java.net.HttpURLConnection;
40 import java.net.MalformedURLException;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
45 public class RetrieveTransactionsTask extends
46 AsyncTask<RetrieveTransactionsTask.Params, RetrieveTransactionsTask.Progress, Void> {
47 private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
48 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\\\"]*>([\\d.-]+)</td>");
49 private static final Pattern transactionDescriptionPattern =
50 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
51 private static final Pattern transactionDetailsPattern =
52 Pattern.compile("^\\s+" + "(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)");
53 private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
54 protected WeakReference<TransactionListActivity> contextRef;
56 private boolean success;
57 public RetrieveTransactionsTask(WeakReference<TransactionListActivity> contextRef) {
58 this.contextRef = contextRef;
60 private static final void L(String msg) {
61 Log.d("transaction-parser", msg);
64 protected void onProgressUpdate(Progress... values) {
65 super.onProgressUpdate(values);
66 TransactionListActivity context = getContext();
67 if (context == null) return;
68 context.onRetrieveProgress(values[0]);
71 protected void onPreExecute() {
73 TransactionListActivity context = getContext();
74 if (context == null) return;
75 context.onRetrieveStart();
78 protected void onPostExecute(Void aVoid) {
79 super.onPostExecute(aVoid);
80 TransactionListActivity context = getContext();
81 if (context == null) return;
82 context.onRetrieveDone(success);
84 @SuppressLint("DefaultLocale")
86 protected Void doInBackground(Params... params) {
87 Progress progress = new Progress();
90 HttpURLConnection http =
91 NetworkUtil.prepare_connection(params[0].getBackendPref(), "journal");
92 http.setAllowUserInteraction(false);
93 publishProgress(progress);
94 TransactionListActivity ctx = contextRef.get();
95 if (ctx == null) return null;
96 try (SQLiteDatabase db = MLDB.getWritableDatabase(ctx)) {
97 try (InputStream resp = http.getInputStream()) {
98 if (http.getResponseCode() != 200) throw new IOException(
99 String.format("HTTP error %d", http.getResponseCode()));
100 db.beginTransaction();
102 db.execSQL("DELETE FROM transactions;");
103 db.execSQL("DELETE FROM transaction_accounts");
105 int state = ParserState.EXPECTING_JOURNAL;
108 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
110 int transactionCount = 0;
111 int transactionId = 0;
112 LedgerTransaction transaction = null;
114 while ((line = buf.readLine()) != null) {
115 if (isCancelled()) break;
117 //L(String.format("State is %d", state));
119 case ParserState.EXPECTING_JOURNAL:
120 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
121 if (line.equals("<h2>General Journal</h2>")) {
122 state = ParserState.EXPECTING_TRANSACTION;
123 L("→ expecting transaction");
126 case ParserState.EXPECTING_TRANSACTION:
127 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
128 m = transactionStartPattern.matcher(line);
130 transactionId = Integer.valueOf(m.group(1));
131 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
133 "found transaction %d → expecting " + "description",
135 progress.setProgress(++transactionCount);
136 if ((progress.getTotal() == Progress.INDETERMINATE) ||
137 (progress.getTotal() < transactionId))
138 progress.setTotal(transactionId);
139 publishProgress(progress);
141 m = endPattern.matcher(line);
143 L("--- transaction list complete ---");
148 case ParserState.EXPECTING_TRANSACTION_DESCRIPTION:
149 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
150 m = transactionDescriptionPattern.matcher(line);
152 if (transactionId == 0)
153 throw new TransactionParserException(
154 "Transaction Id is 0 while expecting " +
158 new LedgerTransaction(transactionId, m.group(1),
160 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
161 L(String.format("transaction %d created for %s (%s) →" +
162 " expecting details", transactionId,
163 m.group(1), m.group(2)));
166 case ParserState.EXPECTING_TRANSACTION_DETAILS:
167 if (line.isEmpty()) {
168 // transaction data collected
169 transaction.insertInto(db);
171 state = ParserState.EXPECTING_TRANSACTION;
173 "transaction %s saved → expecting " + "transaction",
174 transaction.getId()));
176 // sounds like a good idea, but transaction-1 may not be the first one chronologically
177 // for example, when you add the initial seeding transaction after entering some others
178 // if (transactionId == 1) {
179 // L("This was the initial transaction. Terminating " +
185 m = transactionDetailsPattern.matcher(line);
187 String acc_name = m.group(1);
188 String amount = m.group(2);
189 amount = amount.replace(',', '.');
190 transaction.add_item(new LedgerTransactionItem(acc_name,
191 Float.valueOf(amount)));
192 L(String.format("%s = %s", acc_name, amount));
194 else throw new IllegalStateException(
195 String.format("Can't parse transaction details"));
199 throw new RuntimeException(
200 String.format("Unknown " + "parser state %d", state));
203 if (!isCancelled()) db.setTransactionSuccessful();
211 if (success && !isCancelled()) ctx.model.reloadTransactions(ctx);
213 catch (MalformedURLException e) {
214 error = R.string.err_bad_backend_url;
217 catch (FileNotFoundException e) {
218 error = R.string.err_bad_auth;
221 catch (IOException e) {
222 error = R.string.err_net_io_error;
227 TransactionListActivity getContext() {
228 return contextRef.get();
231 public static class Params {
232 static final int DEFAULT_LIMIT = 100;
233 private SharedPreferences backendPref;
234 private String accountsRoot;
237 public Params(SharedPreferences backendPref) {
238 this.backendPref = backendPref;
239 this.accountsRoot = null;
240 this.limit = DEFAULT_LIMIT;
242 Params(SharedPreferences backendPref, String accountsRoot) {
243 this(backendPref, accountsRoot, DEFAULT_LIMIT);
245 Params(SharedPreferences backendPref, String accountsRoot, int limit) {
246 this.backendPref = backendPref;
247 this.accountsRoot = accountsRoot;
250 String getAccountsRoot() {
253 SharedPreferences getBackendPref() {
261 public class Progress {
262 public static final int INDETERMINATE = -1;
263 private int progress;
266 this(INDETERMINATE, INDETERMINATE);
268 Progress(int progress, int total) {
269 this.progress = progress;
272 public int getProgress() {
275 protected void setProgress(int progress) {
276 this.progress = progress;
278 public int getTotal() {
281 protected void setTotal(int total) {
286 private class TransactionParserException extends IllegalStateException {
287 TransactionParserException(String message) {
292 private class ParserState {
293 static final int EXPECTING_JOURNAL = 0;
294 static final int EXPECTING_TRANSACTION = 1;
295 static final int EXPECTING_TRANSACTION_DESCRIPTION = 2;
296 static final int EXPECTING_TRANSACTION_DETAILS = 3;