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.LedgerTransactionAccount;
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.Date;
42 import java.util.regex.Matcher;
43 import java.util.regex.Pattern;
46 public class RetrieveTransactionsTask extends
47 AsyncTask<RetrieveTransactionsTask.Params, RetrieveTransactionsTask.Progress, Void> {
48 private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
49 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\\\"]*>([\\d.-]+)</td>");
50 private static final Pattern transactionDescriptionPattern =
51 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
52 private static final Pattern transactionDetailsPattern =
53 Pattern.compile("^\\s+" + "(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)");
54 private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
55 protected WeakReference<TransactionListActivity> contextRef;
57 private boolean success;
58 public RetrieveTransactionsTask(WeakReference<TransactionListActivity> contextRef) {
59 this.contextRef = contextRef;
61 private static final void L(String msg) {
62 // Log.d("transaction-parser", msg);
65 protected void onProgressUpdate(Progress... values) {
66 super.onProgressUpdate(values);
67 TransactionListActivity context = getContext();
68 if (context == null) return;
69 context.onRetrieveProgress(values[0]);
72 protected void onPreExecute() {
74 TransactionListActivity context = getContext();
75 if (context == null) return;
76 context.onRetrieveStart();
79 protected void onPostExecute(Void aVoid) {
80 super.onPostExecute(aVoid);
81 TransactionListActivity context = getContext();
82 if (context == null) return;
83 context.onRetrieveDone(success);
85 @SuppressLint("DefaultLocale")
87 protected Void doInBackground(Params... params) {
88 Progress progress = new Progress();
89 int maxTransactionId = Progress.INDETERMINATE;
92 HttpURLConnection http =
93 NetworkUtil.prepare_connection(params[0].getBackendPref(), "journal");
94 http.setAllowUserInteraction(false);
95 publishProgress(progress);
96 TransactionListActivity ctx = contextRef.get();
97 if (ctx == null) return null;
98 try (SQLiteDatabase db = MLDB.getWritableDatabase(ctx)) {
99 try (InputStream resp = http.getInputStream()) {
100 if (http.getResponseCode() != 200) throw new IOException(
101 String.format("HTTP error %d", http.getResponseCode()));
102 db.beginTransaction();
104 db.execSQL("UPDATE transactions set keep=0");
106 int state = ParserState.EXPECTING_JOURNAL;
109 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
111 int processedTransactionCount = 0;
112 int transactionId = 0;
113 int matchedTransactionsCount = 0;
114 LedgerTransaction transaction = null;
116 while ((line = buf.readLine()) != null) {
117 if (isCancelled()) break;
119 //L(String.format("State is %d", state));
121 case ParserState.EXPECTING_JOURNAL:
122 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
123 if (line.equals("<h2>General Journal</h2>")) {
124 state = ParserState.EXPECTING_TRANSACTION;
125 L("→ expecting transaction");
128 case ParserState.EXPECTING_TRANSACTION:
129 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
130 m = transactionStartPattern.matcher(line);
132 transactionId = Integer.valueOf(m.group(1));
133 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
135 "found transaction %d → expecting " + "description",
137 progress.setProgress(++processedTransactionCount);
138 if (maxTransactionId < transactionId)
139 maxTransactionId = transactionId;
140 if ((progress.getTotal() == Progress.INDETERMINATE) ||
141 (progress.getTotal() < transactionId))
142 progress.setTotal(transactionId);
143 publishProgress(progress);
145 m = endPattern.matcher(line);
147 L("--- transaction list complete ---");
152 case ParserState.EXPECTING_TRANSACTION_DESCRIPTION:
153 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
154 m = transactionDescriptionPattern.matcher(line);
156 if (transactionId == 0)
157 throw new TransactionParserException(
158 "Transaction Id is 0 while expecting " +
162 new LedgerTransaction(transactionId, m.group(1),
164 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
165 L(String.format("transaction %d created for %s (%s) →" +
166 " expecting details", transactionId,
167 m.group(1), m.group(2)));
170 case ParserState.EXPECTING_TRANSACTION_DETAILS:
171 if (line.isEmpty()) {
172 // transaction data collected
173 if (transaction.existsInDb(db)) {
174 db.execSQL("UPDATE transactions SET keep = 1 WHERE id" +
175 "=?", new Integer[]{transaction.getId()});
176 matchedTransactionsCount++;
178 if (matchedTransactionsCount == 100) {
179 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
181 new Integer[]{transaction.getId()});
183 progress.setTotal(progress.getProgress());
184 publishProgress(progress);
189 db.execSQL("DELETE from transactions WHERE id=?",
190 new Integer[]{transaction.getId()});
191 db.execSQL("DELETE from transaction_accounts WHERE " +
193 new Integer[]{transaction.getId()});
194 transaction.insertInto(db);
195 matchedTransactionsCount = 0;
196 progress.setTotal(maxTransactionId);
199 state = ParserState.EXPECTING_TRANSACTION;
201 "transaction %s saved → expecting " + "transaction",
202 transaction.getId()));
204 // sounds like a good idea, but transaction-1 may not be the first one chronologically
205 // for example, when you add the initial seeding transaction after entering some others
206 // if (transactionId == 1) {
207 // L("This was the initial transaction. Terminating " +
213 m = transactionDetailsPattern.matcher(line);
215 String acc_name = m.group(1);
216 String amount = m.group(2);
217 amount = amount.replace(',', '.');
218 transaction.addAccount(
219 new LedgerTransactionAccount(acc_name,
220 Float.valueOf(amount)));
221 L(String.format("%s = %s", acc_name, amount));
223 else throw new IllegalStateException(
224 String.format("Can't parse transaction %d details",
229 throw new RuntimeException(
230 String.format("Unknown parser state %d", state));
233 if (!isCancelled()) {
234 db.execSQL("DELETE FROM transactions WHERE keep = 0");
235 db.setTransactionSuccessful();
244 if (success && !isCancelled()) {
245 Log.d("db", "Updating transaction list stamp");
246 MLDB.set_option_value(ctx, MLDB.OPT_TRANSACTION_LIST_STAMP, new Date().getTime());
247 ctx.model.reloadTransactions(ctx);
250 catch (MalformedURLException e) {
251 error = R.string.err_bad_backend_url;
254 catch (FileNotFoundException e) {
255 error = R.string.err_bad_auth;
258 catch (IOException e) {
259 error = R.string.err_net_io_error;
264 TransactionListActivity getContext() {
265 return contextRef.get();
268 public static class Params {
269 private SharedPreferences backendPref;
271 public Params(SharedPreferences backendPref) {
272 this.backendPref = backendPref;
274 SharedPreferences getBackendPref() {
279 public class Progress {
280 public static final int INDETERMINATE = -1;
281 private int progress;
284 this(INDETERMINATE, INDETERMINATE);
286 Progress(int progress, int total) {
287 this.progress = progress;
290 public int getProgress() {
293 protected void setProgress(int progress) {
294 this.progress = progress;
296 public int getTotal() {
299 protected void setTotal(int total) {
304 private class TransactionParserException extends IllegalStateException {
305 TransactionParserException(String message) {
310 private class ParserState {
311 static final int EXPECTING_JOURNAL = 0;
312 static final int EXPECTING_TRANSACTION = 1;
313 static final int EXPECTING_TRANSACTION_DESCRIPTION = 2;
314 static final int EXPECTING_TRANSACTION_DETAILS = 3;