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.setTotal(transactionId);
138 publishProgress(progress);
140 m = endPattern.matcher(line);
142 L("--- transaction list complete ---");
147 case ParserState.EXPECTING_TRANSACTION_DESCRIPTION:
148 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
149 m = transactionDescriptionPattern.matcher(line);
151 if (transactionId == 0)
152 throw new TransactionParserException(
153 "Transaction Id is 0 while expecting " +
157 new LedgerTransaction(transactionId, m.group(1),
159 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
160 L(String.format("transaction %d created for %s (%s) →" +
161 " expecting details", transactionId,
162 m.group(1), m.group(2)));
165 case ParserState.EXPECTING_TRANSACTION_DETAILS:
166 if (line.isEmpty()) {
167 // transaction data collected
168 transaction.insertInto(db);
170 state = ParserState.EXPECTING_TRANSACTION;
172 "transaction %s saved → expecting " + "transaction",
173 transaction.getId()));
175 // sounds like a good idea, but transaction-1 may not be the first one chronologically
176 // for example, when you add the initial seeding transaction after entering some others
177 // if (transactionId == 1) {
178 // L("This was the initial transaction. Terminating " +
184 m = transactionDetailsPattern.matcher(line);
186 String acc_name = m.group(1);
187 String amount = m.group(2);
188 amount = amount.replace(',', '.');
189 transaction.add_item(new LedgerTransactionItem(acc_name,
190 Float.valueOf(amount)));
191 L(String.format("%s = %s", acc_name, amount));
193 else throw new IllegalStateException(
194 String.format("Can't parse transaction details"));
198 throw new RuntimeException(
199 String.format("Unknown " + "parser state %d", state));
202 if (!isCancelled()) db.setTransactionSuccessful();
210 if (success && !isCancelled()) ctx.model.reloadTransactions(ctx);
212 catch (MalformedURLException e) {
213 error = R.string.err_bad_backend_url;
216 catch (FileNotFoundException e) {
217 error = R.string.err_bad_auth;
220 catch (IOException e) {
221 error = R.string.err_net_io_error;
226 TransactionListActivity getContext() {
227 return contextRef.get();
230 public static class Params {
231 static final int DEFAULT_LIMIT = 100;
232 private SharedPreferences backendPref;
233 private String accountsRoot;
236 public Params(SharedPreferences backendPref) {
237 this.backendPref = backendPref;
238 this.accountsRoot = null;
239 this.limit = DEFAULT_LIMIT;
241 Params(SharedPreferences backendPref, String accountsRoot) {
242 this(backendPref, accountsRoot, DEFAULT_LIMIT);
244 Params(SharedPreferences backendPref, String accountsRoot, int limit) {
245 this.backendPref = backendPref;
246 this.accountsRoot = accountsRoot;
249 String getAccountsRoot() {
252 SharedPreferences getBackendPref() {
260 public class Progress {
261 public static final int INDETERMINATE = -1;
262 private int progress;
265 this(INDETERMINATE, INDETERMINATE);
267 Progress(int progress, int total) {
268 this.progress = progress;
271 public int getProgress() {
274 protected void setProgress(int progress) {
275 this.progress = progress;
277 public int getTotal() {
280 protected void setTotal(int total) {
285 private class TransactionParserException extends IllegalStateException {
286 TransactionParserException(String message) {
291 private class ParserState {
292 static final int EXPECTING_JOURNAL = 0;
293 static final int EXPECTING_TRANSACTION = 1;
294 static final int EXPECTING_TRANSACTION_DESCRIPTION = 2;
295 static final int EXPECTING_TRANSACTION_DETAILS = 3;