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.utils.MLDB;
34 import net.ktnx.mobileledger.utils.NetworkUtil;
36 import java.io.BufferedReader;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.InputStreamReader;
41 import java.lang.ref.WeakReference;
42 import java.net.HttpURLConnection;
43 import java.net.MalformedURLException;
44 import java.net.URLDecoder;
45 import java.util.ArrayList;
46 import java.util.Date;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
51 public class RetrieveTransactionsTask extends
52 AsyncTask<RetrieveTransactionsTask.Params, RetrieveTransactionsTask.Progress, Void> {
53 public static final int MATCHING_TRANSACTIONS_LIMIT = 50;
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 ArrayList<LedgerTransaction> transactionList = new ArrayList<>();
113 LedgerAccount lastAccount = null;
114 Data.backgroundTaskCount.incrementAndGet();
116 HttpURLConnection http =
117 NetworkUtil.prepare_connection(params[0].getBackendPref(), "journal");
118 http.setAllowUserInteraction(false);
119 publishProgress(progress);
120 MainActivity ctx = getContext();
121 if (ctx == null) return null;
122 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
123 try (InputStream resp = http.getInputStream()) {
124 if (http.getResponseCode() != 200) throw new IOException(
125 String.format("HTTP error %d", http.getResponseCode()));
126 db.beginTransaction();
128 db.execSQL("UPDATE transactions set keep=0");
129 db.execSQL("update account_values set keep=0;");
130 db.execSQL("update accounts set keep=0;");
132 ParserState state = ParserState.EXPECTING_ACCOUNT;
135 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
137 int processedTransactionCount = 0;
138 int transactionId = 0;
139 int matchedTransactionsCount = 0;
140 LedgerTransaction transaction = null;
142 while ((line = buf.readLine()) != null) {
145 //L(String.format("State is %d", updating));
147 case EXPECTING_ACCOUNT:
148 if (line.equals("<h2>General Journal</h2>")) {
149 state = ParserState.EXPECTING_TRANSACTION;
150 L("→ expecting transaction");
151 Data.accounts.set(accountList);
154 m = account_name_re.matcher(line);
156 String acct_encoded = m.group(1);
157 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
158 acct_name = acct_name.replace("\"", "");
159 L(String.format("found account: %s", acct_name));
161 addAccount(db, acct_name);
162 lastAccount = new LedgerAccount(acct_name);
163 accountList.add(lastAccount);
165 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
166 L("→ expecting account amount");
170 case EXPECTING_ACCOUNT_AMOUNT:
171 m = account_value_re.matcher(line);
172 boolean match_found = false;
177 String value = m.group(1);
178 String currency = m.group(2);
179 if (currency == null) currency = "";
180 value = value.replace(',', '.');
181 L("curr=" + currency + ", value=" + value);
183 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
184 new Object[]{lastAccount.getName(), currency,
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 ==
250 MATCHING_TRANSACTIONS_LIMIT)
252 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
254 new Integer[]{transaction.getId()});
256 progress.setTotal(progress.getProgress());
257 publishProgress(progress);
262 db.execSQL("DELETE from transactions WHERE id=?",
263 new Integer[]{transaction.getId()});
264 db.execSQL("DELETE from transaction_accounts WHERE " +
266 new Integer[]{transaction.getId()});
267 transaction.insertInto(db);
268 matchedTransactionsCount = 0;
269 progress.setTotal(maxTransactionId);
272 state = ParserState.EXPECTING_TRANSACTION;
274 "transaction %s saved → expecting transaction",
275 transaction.getId()));
276 transactionList.add(transaction);
278 // sounds like a good idea, but transaction-1 may not be the first one chronologically
279 // for example, when you add the initial seeding transaction after entering some others
280 // if (transactionId == 1) {
281 // L("This was the initial transaction. Terminating " +
287 m = transactionDetailsPattern.matcher(line);
289 String acc_name = m.group(1);
290 String amount = m.group(2);
291 String currency = m.group(3);
292 amount = amount.replace(',', '.');
293 transaction.addAccount(
294 new LedgerTransactionAccount(acc_name,
295 Float.valueOf(amount), currency));
296 L(String.format("%s = %s", acc_name, amount));
298 else throw new IllegalStateException(
299 String.format("Can't parse transaction %d details",
304 throw new RuntimeException(
305 String.format("Unknown parser updating %s",
312 db.execSQL("DELETE FROM transactions WHERE keep = 0");
313 db.setTransactionSuccessful();
315 Log.d("db", "Updating transaction value stamp");
316 Date now = new Date();
317 MLDB.set_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, now.getTime());
318 Data.lastUpdateDate.set(now);
319 Data.transactions.set(transactionList);
327 catch (MalformedURLException e) {
328 error = R.string.err_bad_backend_url;
331 catch (FileNotFoundException e) {
332 error = R.string.err_bad_auth;
335 catch (IOException e) {
336 error = R.string.err_net_io_error;
339 catch (OperationCanceledException e) {
340 error = R.string.err_cancelled;
344 Data.backgroundTaskCount.decrementAndGet();
348 private MainActivity getContext() {
349 return contextRef.get();
351 private void addAccount(SQLiteDatabase db, String name) {
353 LedgerAccount acc = new LedgerAccount(name);
354 db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
355 new Object[]{acc.getLevel(), name});
356 db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
357 "?,? " + "where (select changes() = 0)",
358 new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
359 name = acc.getParentName();
360 } while (name != null);
362 private void throwIfCancelled() {
363 if (isCancelled()) throw new OperationCanceledException(null);
366 private enum ParserState {
367 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
368 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
371 public static class Params {
372 private SharedPreferences backendPref;
374 public Params(SharedPreferences backendPref) {
375 this.backendPref = backendPref;
377 SharedPreferences getBackendPref() {
382 public class Progress {
383 public static final int INDETERMINATE = -1;
384 private int progress;
387 this(INDETERMINATE, INDETERMINATE);
389 Progress(int progress, int total) {
390 this.progress = progress;
393 public int getProgress() {
396 protected void setProgress(int progress) {
397 this.progress = progress;
399 public int getTotal() {
402 protected void setTotal(int total) {
407 private class TransactionParserException extends IllegalStateException {
408 TransactionParserException(String message) {