2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe 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 * MoLe 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 MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.async;
20 import android.annotation.SuppressLint;
21 import android.os.OperationCanceledException;
23 import androidx.annotation.NonNull;
25 import com.fasterxml.jackson.core.JsonParseException;
26 import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
28 import net.ktnx.mobileledger.dao.AccountDAO;
29 import net.ktnx.mobileledger.dao.TransactionDAO;
30 import net.ktnx.mobileledger.db.Account;
31 import net.ktnx.mobileledger.db.AccountWithAmounts;
32 import net.ktnx.mobileledger.db.DB;
33 import net.ktnx.mobileledger.db.Option;
34 import net.ktnx.mobileledger.db.Profile;
35 import net.ktnx.mobileledger.db.TransactionWithAccounts;
36 import net.ktnx.mobileledger.err.HTTPException;
37 import net.ktnx.mobileledger.json.API;
38 import net.ktnx.mobileledger.json.AccountListParser;
39 import net.ktnx.mobileledger.json.ApiNotSupportedException;
40 import net.ktnx.mobileledger.json.TransactionListParser;
41 import net.ktnx.mobileledger.model.Data;
42 import net.ktnx.mobileledger.model.LedgerAccount;
43 import net.ktnx.mobileledger.model.LedgerTransaction;
44 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
45 import net.ktnx.mobileledger.utils.Logger;
46 import net.ktnx.mobileledger.utils.NetworkUtil;
48 import java.io.BufferedReader;
49 import java.io.IOException;
50 import java.io.InputStream;
51 import java.io.InputStreamReader;
52 import java.net.HttpURLConnection;
53 import java.net.MalformedURLException;
54 import java.net.URLDecoder;
55 import java.nio.charset.StandardCharsets;
56 import java.text.ParseException;
57 import java.util.ArrayList;
58 import java.util.Collections;
59 import java.util.Date;
60 import java.util.HashMap;
61 import java.util.List;
62 import java.util.Locale;
63 import java.util.Objects;
64 import java.util.regex.Matcher;
65 import java.util.regex.Pattern;
68 public class RetrieveTransactionsTask extends Thread {
69 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
70 private static final Pattern reComment = Pattern.compile("^\\s*;");
71 private static final Pattern reTransactionStart = Pattern.compile(
72 "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
73 "\"[^\"]*>([\\d.-]+)</td>");
74 private static final Pattern reTransactionDescription =
75 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
76 private static final Pattern reTransactionDetails = Pattern.compile(
77 "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
78 "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
79 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
80 private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
81 private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
82 private static final String TAG = "RTT";
84 private final Pattern reAccountName =
85 Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
86 private final Pattern reAccountValue = Pattern.compile(
87 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
88 private final Profile profile;
89 private int expectedPostingsCount = -1;
90 public RetrieveTransactionsTask(@NonNull Profile profile) {
91 this.profile = profile;
93 private static void L(String msg) {
94 //debug("transaction-parser", msg);
96 static LedgerTransactionAccount parseTransactionAccountLine(String line) {
97 Matcher m = reTransactionDetails.matcher(line);
99 String postingStatus = m.group(1);
100 String acc_name = m.group(2);
101 String currencyPre = m.group(3);
102 String amount = Objects.requireNonNull(m.group(4));
103 String currencyPost = m.group(5);
105 String currency = null;
106 if ((currencyPre != null) && (currencyPre.length() > 0)) {
107 if ((currencyPost != null) && (currencyPost.length() > 0))
109 currency = currencyPre;
111 else if ((currencyPost != null) && (currencyPost.length() > 0)) {
112 currency = currencyPost;
115 amount = amount.replace(',', '.');
117 return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
123 private void publishProgress(Progress progress) {
124 Data.backgroundTaskProgress.postValue(progress);
126 private void finish(Result result) {
127 Progress progress = new Progress();
128 progress.setState(ProgressState.FINISHED);
129 progress.setError(result.error);
130 publishProgress(progress);
132 private void cancel() {
133 Progress progress = new Progress();
134 progress.setState(ProgressState.FINISHED);
135 publishProgress(progress);
137 private void retrieveTransactionListLegacy(List<LedgerAccount> accounts,
138 List<LedgerTransaction> transactions)
139 throws IOException, HTTPException {
140 Progress progress = Progress.indeterminate();
141 progress.setState(ProgressState.RUNNING);
142 progress.setTotal(expectedPostingsCount);
143 int maxTransactionId = -1;
144 HashMap<String, LedgerAccount> map = new HashMap<>();
145 LedgerAccount lastAccount = null;
146 ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
148 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
149 http.setAllowUserInteraction(false);
150 publishProgress(progress);
151 if (http.getResponseCode() != 200)
152 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
154 try (InputStream resp = http.getInputStream()) {
155 if (http.getResponseCode() != 200)
156 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
158 int matchedTransactionsCount = 0;
160 ParserState state = ParserState.EXPECTING_ACCOUNT;
163 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
165 int processedTransactionCount = 0;
166 int transactionId = 0;
167 LedgerTransaction transaction = null;
169 while ((line = buf.readLine()) != null) {
172 m = reComment.matcher(line);
174 // TODO: comments are ignored for now
175 // Log.v("transaction-parser", "Ignoring comment");
178 //L(String.format("State is %d", updating));
180 case EXPECTING_ACCOUNT:
181 if (line.equals("<h2>General Journal</h2>")) {
182 state = ParserState.EXPECTING_TRANSACTION;
183 L("→ expecting transaction");
186 m = reAccountName.matcher(line);
188 String acct_encoded = m.group(1);
189 String accName = URLDecoder.decode(acct_encoded, "UTF-8");
190 accName = accName.replace("\"", "");
191 L(String.format("found account: %s", accName));
193 lastAccount = map.get(accName);
194 if (lastAccount != null) {
195 L(String.format("ignoring duplicate account '%s'", accName));
198 String parentAccountName = LedgerAccount.extractParentName(accName);
199 LedgerAccount parentAccount;
200 if (parentAccountName != null) {
201 parentAccount = ensureAccountExists(parentAccountName, map,
205 parentAccount = null;
207 lastAccount = new LedgerAccount(accName, parentAccount);
209 accounts.add(lastAccount);
210 map.put(accName, lastAccount);
212 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
213 L("→ expecting account amount");
217 case EXPECTING_ACCOUNT_AMOUNT:
218 m = reAccountValue.matcher(line);
219 boolean match_found = false;
224 String value = Objects.requireNonNull(m.group(1));
225 String currency = m.group(2);
226 if (currency == null)
230 Matcher tmpM = reDecimalComma.matcher(value);
232 value = value.replace(".", "");
233 value = value.replace(',', '.');
236 tmpM = reDecimalPoint.matcher(value);
238 value = value.replace(",", "");
239 value = value.replace(" ", "");
242 L("curr=" + currency + ", value=" + value);
243 final float val = Float.parseFloat(value);
244 lastAccount.addAmount(val, currency);
245 for (LedgerAccount syn : syntheticAccounts) {
246 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
247 currency, val, syn.getName()));
248 syn.addAmount(val, currency);
253 syntheticAccounts.clear();
254 state = ParserState.EXPECTING_ACCOUNT;
255 L("→ expecting account");
260 case EXPECTING_TRANSACTION:
261 if (!line.isEmpty() && (line.charAt(0) == ' '))
263 m = reTransactionStart.matcher(line);
265 transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
266 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
267 L(String.format(Locale.ENGLISH,
268 "found transaction %d → expecting description", transactionId));
269 progress.setProgress(++processedTransactionCount);
270 if (maxTransactionId < transactionId)
271 maxTransactionId = transactionId;
272 if ((progress.isIndeterminate()) ||
273 (progress.getTotal() < transactionId))
274 progress.setTotal(transactionId);
275 publishProgress(progress);
277 m = reEnd.matcher(line);
279 L("--- transaction value complete ---");
284 case EXPECTING_TRANSACTION_DESCRIPTION:
285 if (!line.isEmpty() && (line.charAt(0) == ' '))
287 m = reTransactionDescription.matcher(line);
289 if (transactionId == 0)
290 throw new TransactionParserException(
291 "Transaction Id is 0 while expecting description");
293 String date = Objects.requireNonNull(m.group(1));
295 int equalsIndex = date.indexOf('=');
296 if (equalsIndex >= 0)
297 date = date.substring(equalsIndex + 1);
299 new LedgerTransaction(transactionId, date, m.group(2));
301 catch (ParseException e) {
302 throw new TransactionParserException(
303 String.format("Error parsing date '%s'", date));
305 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
306 L(String.format(Locale.ENGLISH,
307 "transaction %d created for %s (%s) →" + " expecting details",
308 transactionId, date, m.group(2)));
312 case EXPECTING_TRANSACTION_DETAILS:
313 if (line.isEmpty()) {
314 // transaction data collected
316 transaction.finishLoading();
317 transactions.add(transaction);
319 state = ParserState.EXPECTING_TRANSACTION;
320 L(String.format("transaction %s parsed → expecting transaction",
321 transaction.getLedgerId()));
323 // sounds like a good idea, but transaction-1 may not be the first one chronologically
324 // for example, when you add the initial seeding transaction after entering some others
325 // if (transactionId == 1) {
326 // L("This was the initial transaction.
333 LedgerTransactionAccount lta = parseTransactionAccountLine(line);
335 transaction.addAccount(lta);
336 L(String.format(Locale.ENGLISH, "%d: %s = %s",
337 transaction.getLedgerId(), lta.getAccountName(),
341 throw new IllegalStateException(
342 String.format("Can't parse transaction %d details: %s",
343 transactionId, line));
347 throw new RuntimeException(
348 String.format("Unknown parser updating %s", state.name()));
356 public LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
357 ArrayList<LedgerAccount> createdAccounts) {
358 LedgerAccount acc = map.get(accountName);
363 String parentName = LedgerAccount.extractParentName(accountName);
364 LedgerAccount parentAccount;
365 if (parentName != null) {
366 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
369 parentAccount = null;
372 acc = new LedgerAccount(accountName, parentAccount);
373 createdAccounts.add(acc);
376 public void addNumberOfPostings(int number) {
377 expectedPostingsCount += number;
379 private List<LedgerAccount> retrieveAccountList()
380 throws IOException, HTTPException, ApiNotSupportedException {
381 final API apiVersion = API.valueOf(profile.getApiVersion());
382 if (apiVersion.equals(API.auto)) {
383 return retrieveAccountListAnyVersion();
385 else if (apiVersion.equals(API.html)) {
387 "Declining using JSON API for /accounts with configured legacy API version");
391 return retrieveAccountListForVersion(apiVersion);
394 private List<LedgerAccount> retrieveAccountListAnyVersion()
395 throws ApiNotSupportedException, IOException, HTTPException {
396 for (API ver : API.allVersions) {
398 return retrieveAccountListForVersion(ver);
400 catch (JsonParseException | RuntimeJsonMappingException e) {
402 String.format(Locale.US, "Error during account list retrieval using API %s",
403 ver.getDescription()), e);
408 throw new ApiNotSupportedException();
410 private List<LedgerAccount> retrieveAccountListForVersion(API version)
411 throws IOException, HTTPException {
412 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
413 http.setAllowUserInteraction(false);
414 switch (http.getResponseCode()) {
420 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
422 publishProgress(Progress.indeterminate());
423 ArrayList<LedgerAccount> list = new ArrayList<>();
424 HashMap<String, LedgerAccount> map = new HashMap<>();
426 try (InputStream resp = http.getInputStream()) {
428 if (http.getResponseCode() != 200)
429 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
431 AccountListParser parser = AccountListParser.forApiVersion(version, resp);
432 expectedPostingsCount = 0;
436 LedgerAccount acc = parser.nextAccount(this, map);
446 private List<LedgerTransaction> retrieveTransactionList()
447 throws ParseException, HTTPException, IOException, ApiNotSupportedException {
448 final API apiVersion = API.valueOf(profile.getApiVersion());
449 if (apiVersion.equals(API.auto)) {
450 return retrieveTransactionListAnyVersion();
452 else if (apiVersion.equals(API.html)) {
454 "Declining using JSON API for /accounts with configured legacy API version");
458 return retrieveTransactionListForVersion(apiVersion);
462 private List<LedgerTransaction> retrieveTransactionListAnyVersion()
463 throws ApiNotSupportedException {
464 for (API ver : API.allVersions) {
466 return retrieveTransactionListForVersion(ver);
468 catch (Exception e) {
470 String.format(Locale.US, "Error during account list retrieval using API %s",
471 ver.getDescription()));
476 throw new ApiNotSupportedException();
478 private List<LedgerTransaction> retrieveTransactionListForVersion(API apiVersion)
479 throws IOException, ParseException, HTTPException {
480 Progress progress = new Progress();
481 progress.setTotal(expectedPostingsCount);
483 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
484 http.setAllowUserInteraction(false);
485 publishProgress(progress);
486 switch (http.getResponseCode()) {
492 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
494 ArrayList<LedgerTransaction> trList = new ArrayList<>();
495 try (InputStream resp = http.getInputStream()) {
498 TransactionListParser parser = TransactionListParser.forApiVersion(apiVersion, resp);
500 int processedPostings = 0;
504 LedgerTransaction transaction = parser.nextTransaction();
506 if (transaction == null)
509 trList.add(transaction);
511 progress.setProgress(processedPostings += transaction.getAccounts()
513 // Logger.debug("trParser",
514 // String.format(Locale.US, "Parsed transaction %d - %s", transaction
516 // transaction.getDescription()));
517 // for (LedgerTransactionAccount acc : transaction.getAccounts()) {
518 // Logger.debug("trParser",
519 // String.format(Locale.US, " %s", acc.getAccountName()));
521 publishProgress(progress);
527 // json interface returns transactions if file order and the rest of the machinery
528 // expects them in reverse chronological order
529 Collections.sort(trList, (o1, o2) -> {
530 int res = o2.getDate()
531 .compareTo(o1.getDate());
534 return Long.compare(o2.getLedgerId(), o1.getLedgerId());
539 @SuppressLint("DefaultLocale")
542 Data.backgroundTaskStarted();
543 List<LedgerAccount> accounts;
544 List<LedgerTransaction> transactions;
546 accounts = retrieveAccountList();
547 // accounts is null in API-version auto-detection and means
548 // requesting 'html' API version via the JSON classes
549 // this can't work, and the null results in the legacy code below
551 if (accounts == null)
554 transactions = retrieveTransactionList();
556 if (accounts == null || transactions == null) {
557 accounts = new ArrayList<>();
558 transactions = new ArrayList<>();
559 retrieveTransactionListLegacy(accounts, transactions);
562 new AccountAndTransactionListSaver(accounts, transactions).start();
564 Data.lastUpdateDate.postValue(new Date());
566 finish(new Result(null));
568 catch (MalformedURLException e) {
570 finish(new Result("Invalid server URL"));
572 catch (HTTPException e) {
575 String.format("HTTP error %d: %s", e.getResponseCode(), e.getMessage())));
577 catch (IOException e) {
579 finish(new Result(e.getLocalizedMessage()));
581 catch (RuntimeJsonMappingException e) {
583 finish(new Result(Result.ERR_JSON_PARSER_ERROR));
585 catch (ParseException e) {
587 finish(new Result("Network error"));
589 catch (OperationCanceledException e) {
590 Logger.debug("RTT", "Retrieval was cancelled", e);
591 finish(new Result(null));
593 catch (ApiNotSupportedException e) {
595 finish(new Result("Server version not supported"));
598 Data.backgroundTaskFinished();
601 public void throwIfCancelled() {
603 throw new OperationCanceledException(null);
605 private enum ParserState {
606 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
607 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
610 public enum ProgressState {STARTING, RUNNING, FINISHED}
612 public static class Progress {
613 private int progress;
615 private ProgressState state = ProgressState.RUNNING;
616 private String error = null;
617 private boolean indeterminate;
619 indeterminate = true;
621 Progress(int progress, int total) {
622 this.indeterminate = false;
623 this.progress = progress;
626 public static Progress indeterminate() {
627 return new Progress();
629 public static Progress finished(String error) {
630 Progress p = new Progress();
631 p.setState(ProgressState.FINISHED);
635 public int getProgress() {
636 ensureState(ProgressState.RUNNING);
639 protected void setProgress(int progress) {
640 this.progress = progress;
641 this.state = ProgressState.RUNNING;
643 public int getTotal() {
644 ensureState(ProgressState.RUNNING);
647 protected void setTotal(int total) {
649 state = ProgressState.RUNNING;
650 indeterminate = total == -1;
652 private void ensureState(ProgressState wanted) {
654 throw new IllegalStateException(
655 String.format("Bad state: %s, expected %s", state, wanted));
657 public ProgressState getState() {
660 public void setState(ProgressState state) {
663 public String getError() {
664 ensureState(ProgressState.FINISHED);
667 public void setError(String error) {
669 state = ProgressState.FINISHED;
671 public boolean isIndeterminate() {
672 return indeterminate;
674 public void setIndeterminate(boolean indeterminate) {
675 this.indeterminate = indeterminate;
679 private static class TransactionParserException extends IllegalStateException {
680 TransactionParserException(String message) {
685 public static class Result {
686 public static String ERR_JSON_PARSER_ERROR = "err_json_parser";
688 public List<LedgerAccount> accounts;
689 public List<LedgerTransaction> transactions;
690 Result(String error) {
693 Result(List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
694 this.accounts = accounts;
695 this.transactions = transactions;
699 private class AccountAndTransactionListSaver extends Thread {
700 private final List<LedgerAccount> accounts;
701 private final List<LedgerTransaction> transactions;
702 public AccountAndTransactionListSaver(List<LedgerAccount> accounts,
703 List<LedgerTransaction> transactions) {
704 this.accounts = accounts;
705 this.transactions = transactions;
709 AccountDAO accDao = DB.get()
711 TransactionDAO trDao = DB.get()
712 .getTransactionDAO();
714 Logger.debug(TAG, "Preparing account list");
715 final List<AccountWithAmounts> list = new ArrayList<>();
716 for (LedgerAccount acc : accounts) {
717 final AccountWithAmounts a = acc.toDBOWithAmounts();
718 Account existing = accDao.getByNameSync(profile.getId(), acc.getName());
719 if (existing != null) {
720 a.account.setExpanded(existing.isExpanded());
721 a.account.setAmountsExpanded(existing.isAmountsExpanded());
722 a.account.setId(existing.getId()); // not strictly needed, but since we have it
728 Logger.debug(TAG, "Account list prepared. Storing");
729 accDao.storeAccountsSync(list, profile.getId());
730 Logger.debug(TAG, "Account list stored");
732 Logger.debug(TAG, "Preparing transaction list");
733 final List<TransactionWithAccounts> tranList = new ArrayList<>();
735 for (LedgerTransaction tr : transactions)
736 tranList.add(tr.toDBO());
738 Logger.debug(TAG, "Storing transaction list");
739 trDao.storeTransactionsSync(tranList, profile.getId());
741 Logger.debug(TAG, "Transactions stored");
745 .insertSync(new Option(profile.getId(), Option.OPT_LAST_SCRAPE,
746 String.valueOf((new Date()).getTime())));