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.AsyncTask;
22 import android.os.OperationCanceledException;
24 import androidx.annotation.NonNull;
26 import com.fasterxml.jackson.core.JsonParseException;
27 import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
29 import net.ktnx.mobileledger.dao.AccountDAO;
30 import net.ktnx.mobileledger.dao.TransactionDAO;
31 import net.ktnx.mobileledger.db.Account;
32 import net.ktnx.mobileledger.db.AccountWithAmounts;
33 import net.ktnx.mobileledger.db.DB;
34 import net.ktnx.mobileledger.db.Option;
35 import net.ktnx.mobileledger.db.Profile;
36 import net.ktnx.mobileledger.db.TransactionWithAccounts;
37 import net.ktnx.mobileledger.err.HTTPException;
38 import net.ktnx.mobileledger.json.API;
39 import net.ktnx.mobileledger.json.AccountListParser;
40 import net.ktnx.mobileledger.json.ApiNotSupportedException;
41 import net.ktnx.mobileledger.json.TransactionListParser;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerAccount;
44 import net.ktnx.mobileledger.model.LedgerTransaction;
45 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
46 import net.ktnx.mobileledger.ui.MainModel;
47 import net.ktnx.mobileledger.utils.Logger;
48 import net.ktnx.mobileledger.utils.NetworkUtil;
50 import java.io.BufferedReader;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.io.InputStreamReader;
54 import java.net.HttpURLConnection;
55 import java.net.MalformedURLException;
56 import java.net.URLDecoder;
57 import java.nio.charset.StandardCharsets;
58 import java.text.ParseException;
59 import java.util.ArrayList;
60 import java.util.Collections;
61 import java.util.Date;
62 import java.util.HashMap;
63 import java.util.List;
64 import java.util.Locale;
65 import java.util.Objects;
66 import java.util.regex.Matcher;
67 import java.util.regex.Pattern;
70 public class RetrieveTransactionsTask extends
71 AsyncTask<Void, RetrieveTransactionsTask.Progress, RetrieveTransactionsTask.Result> {
72 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
73 private static final Pattern reComment = Pattern.compile("^\\s*;");
74 private static final Pattern reTransactionStart = Pattern.compile(
75 "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
76 "\"[^\"]*>([\\d.-]+)</td>");
77 private static final Pattern reTransactionDescription =
78 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
79 private static final Pattern reTransactionDetails = Pattern.compile(
80 "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
81 "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
82 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
83 private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
84 private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
85 private static final String TAG = "RTT";
87 private final Pattern reAccountName =
88 Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
89 private final Pattern reAccountValue = Pattern.compile(
90 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
91 private final MainModel mainModel;
92 private final Profile profile;
93 private int expectedPostingsCount = -1;
94 public RetrieveTransactionsTask(@NonNull MainModel mainModel, @NonNull Profile profile) {
95 this.mainModel = mainModel;
96 this.profile = profile;
98 private static void L(String msg) {
99 //debug("transaction-parser", msg);
101 static LedgerTransactionAccount parseTransactionAccountLine(String line) {
102 Matcher m = reTransactionDetails.matcher(line);
104 String postingStatus = m.group(1);
105 String acc_name = m.group(2);
106 String currencyPre = m.group(3);
107 String amount = Objects.requireNonNull(m.group(4));
108 String currencyPost = m.group(5);
110 String currency = null;
111 if ((currencyPre != null) && (currencyPre.length() > 0)) {
112 if ((currencyPost != null) && (currencyPost.length() > 0))
114 currency = currencyPre;
116 else if ((currencyPost != null) && (currencyPost.length() > 0)) {
117 currency = currencyPost;
120 amount = amount.replace(',', '.');
122 return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
129 protected void onProgressUpdate(Progress... values) {
130 super.onProgressUpdate(values);
131 Data.backgroundTaskProgress.postValue(values[0]);
134 protected void onPostExecute(Result result) {
135 super.onPostExecute(result);
136 Progress progress = new Progress();
137 progress.setState(ProgressState.FINISHED);
138 progress.setError(result.error);
139 onProgressUpdate(progress);
142 protected void onCancelled() {
144 Progress progress = new Progress();
145 progress.setState(ProgressState.FINISHED);
146 onProgressUpdate(progress);
148 private void retrieveTransactionListLegacy(List<LedgerAccount> accounts,
149 List<LedgerTransaction> transactions)
150 throws IOException, HTTPException {
151 Progress progress = Progress.indeterminate();
152 progress.setState(ProgressState.RUNNING);
153 progress.setTotal(expectedPostingsCount);
154 int maxTransactionId = -1;
155 HashMap<String, LedgerAccount> map = new HashMap<>();
156 LedgerAccount lastAccount = null;
157 ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
159 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
160 http.setAllowUserInteraction(false);
161 publishProgress(progress);
162 if (http.getResponseCode() != 200)
163 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
165 try (InputStream resp = http.getInputStream()) {
166 if (http.getResponseCode() != 200)
167 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
169 int matchedTransactionsCount = 0;
171 ParserState state = ParserState.EXPECTING_ACCOUNT;
174 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
176 int processedTransactionCount = 0;
177 int transactionId = 0;
178 LedgerTransaction transaction = null;
180 while ((line = buf.readLine()) != null) {
183 m = reComment.matcher(line);
185 // TODO: comments are ignored for now
186 // Log.v("transaction-parser", "Ignoring comment");
189 //L(String.format("State is %d", updating));
191 case EXPECTING_ACCOUNT:
192 if (line.equals("<h2>General Journal</h2>")) {
193 state = ParserState.EXPECTING_TRANSACTION;
194 L("→ expecting transaction");
197 m = reAccountName.matcher(line);
199 String acct_encoded = m.group(1);
200 String accName = URLDecoder.decode(acct_encoded, "UTF-8");
201 accName = accName.replace("\"", "");
202 L(String.format("found account: %s", accName));
204 lastAccount = map.get(accName);
205 if (lastAccount != null) {
206 L(String.format("ignoring duplicate account '%s'", accName));
209 String parentAccountName = LedgerAccount.extractParentName(accName);
210 LedgerAccount parentAccount;
211 if (parentAccountName != null) {
212 parentAccount = ensureAccountExists(parentAccountName, map,
216 parentAccount = null;
218 lastAccount = new LedgerAccount(accName, parentAccount);
220 accounts.add(lastAccount);
221 map.put(accName, lastAccount);
223 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
224 L("→ expecting account amount");
228 case EXPECTING_ACCOUNT_AMOUNT:
229 m = reAccountValue.matcher(line);
230 boolean match_found = false;
235 String value = Objects.requireNonNull(m.group(1));
236 String currency = m.group(2);
237 if (currency == null)
241 Matcher tmpM = reDecimalComma.matcher(value);
243 value = value.replace(".", "");
244 value = value.replace(',', '.');
247 tmpM = reDecimalPoint.matcher(value);
249 value = value.replace(",", "");
250 value = value.replace(" ", "");
253 L("curr=" + currency + ", value=" + value);
254 final float val = Float.parseFloat(value);
255 lastAccount.addAmount(val, currency);
256 for (LedgerAccount syn : syntheticAccounts) {
257 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
258 currency, val, syn.getName()));
259 syn.addAmount(val, currency);
264 syntheticAccounts.clear();
265 state = ParserState.EXPECTING_ACCOUNT;
266 L("→ expecting account");
271 case EXPECTING_TRANSACTION:
272 if (!line.isEmpty() && (line.charAt(0) == ' '))
274 m = reTransactionStart.matcher(line);
276 transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
277 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
278 L(String.format(Locale.ENGLISH,
279 "found transaction %d → expecting description", transactionId));
280 progress.setProgress(++processedTransactionCount);
281 if (maxTransactionId < transactionId)
282 maxTransactionId = transactionId;
283 if ((progress.isIndeterminate()) ||
284 (progress.getTotal() < transactionId))
285 progress.setTotal(transactionId);
286 publishProgress(progress);
288 m = reEnd.matcher(line);
290 L("--- transaction value complete ---");
295 case EXPECTING_TRANSACTION_DESCRIPTION:
296 if (!line.isEmpty() && (line.charAt(0) == ' '))
298 m = reTransactionDescription.matcher(line);
300 if (transactionId == 0)
301 throw new TransactionParserException(
302 "Transaction Id is 0 while expecting description");
304 String date = Objects.requireNonNull(m.group(1));
306 int equalsIndex = date.indexOf('=');
307 if (equalsIndex >= 0)
308 date = date.substring(equalsIndex + 1);
310 new LedgerTransaction(transactionId, date, m.group(2));
312 catch (ParseException e) {
313 throw new TransactionParserException(
314 String.format("Error parsing date '%s'", date));
316 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
317 L(String.format(Locale.ENGLISH,
318 "transaction %d created for %s (%s) →" + " expecting details",
319 transactionId, date, m.group(2)));
323 case EXPECTING_TRANSACTION_DETAILS:
324 if (line.isEmpty()) {
325 // transaction data collected
327 transaction.finishLoading();
328 transactions.add(transaction);
330 state = ParserState.EXPECTING_TRANSACTION;
331 L(String.format("transaction %s parsed → expecting transaction",
332 transaction.getLedgerId()));
334 // sounds like a good idea, but transaction-1 may not be the first one chronologically
335 // for example, when you add the initial seeding transaction after entering some others
336 // if (transactionId == 1) {
337 // L("This was the initial transaction.
344 LedgerTransactionAccount lta = parseTransactionAccountLine(line);
346 transaction.addAccount(lta);
347 L(String.format(Locale.ENGLISH, "%d: %s = %s",
348 transaction.getLedgerId(), lta.getAccountName(),
352 throw new IllegalStateException(
353 String.format("Can't parse transaction %d details: %s",
354 transactionId, line));
358 throw new RuntimeException(
359 String.format("Unknown parser updating %s", state.name()));
367 public LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
368 ArrayList<LedgerAccount> createdAccounts) {
369 LedgerAccount acc = map.get(accountName);
374 String parentName = LedgerAccount.extractParentName(accountName);
375 LedgerAccount parentAccount;
376 if (parentName != null) {
377 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
380 parentAccount = null;
383 acc = new LedgerAccount(accountName, parentAccount);
384 createdAccounts.add(acc);
387 public void addNumberOfPostings(int number) {
388 expectedPostingsCount += number;
390 private List<LedgerAccount> retrieveAccountList()
391 throws IOException, HTTPException, ApiNotSupportedException {
392 final API apiVersion = API.valueOf(profile.getApiVersion());
393 if (apiVersion.equals(API.auto)) {
394 return retrieveAccountListAnyVersion();
396 else if (apiVersion.equals(API.html)) {
398 "Declining using JSON API for /accounts with configured legacy API version");
402 return retrieveAccountListForVersion(apiVersion);
405 private List<LedgerAccount> retrieveAccountListAnyVersion()
406 throws ApiNotSupportedException, IOException, HTTPException {
407 for (API ver : API.allVersions) {
409 return retrieveAccountListForVersion(ver);
411 catch (JsonParseException | RuntimeJsonMappingException e) {
413 String.format(Locale.US, "Error during account list retrieval using API %s",
414 ver.getDescription()), e);
419 throw new ApiNotSupportedException();
421 private List<LedgerAccount> retrieveAccountListForVersion(API version)
422 throws IOException, HTTPException {
423 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
424 http.setAllowUserInteraction(false);
425 switch (http.getResponseCode()) {
431 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
433 publishProgress(Progress.indeterminate());
434 ArrayList<LedgerAccount> list = new ArrayList<>();
435 HashMap<String, LedgerAccount> map = new HashMap<>();
437 try (InputStream resp = http.getInputStream()) {
439 if (http.getResponseCode() != 200)
440 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
442 AccountListParser parser = AccountListParser.forApiVersion(version, resp);
443 expectedPostingsCount = 0;
447 LedgerAccount acc = parser.nextAccount(this, map);
457 private List<LedgerTransaction> retrieveTransactionList()
458 throws ParseException, HTTPException, IOException, ApiNotSupportedException {
459 final API apiVersion = API.valueOf(profile.getApiVersion());
460 if (apiVersion.equals(API.auto)) {
461 return retrieveTransactionListAnyVersion();
463 else if (apiVersion.equals(API.html)) {
465 "Declining using JSON API for /accounts with configured legacy API version");
469 return retrieveTransactionListForVersion(apiVersion);
473 private List<LedgerTransaction> retrieveTransactionListAnyVersion()
474 throws ApiNotSupportedException {
475 for (API ver : API.allVersions) {
477 return retrieveTransactionListForVersion(ver);
479 catch (Exception e) {
481 String.format(Locale.US, "Error during account list retrieval using API %s",
482 ver.getDescription()));
487 throw new ApiNotSupportedException();
489 private List<LedgerTransaction> retrieveTransactionListForVersion(API apiVersion)
490 throws IOException, ParseException, HTTPException {
491 Progress progress = new Progress();
492 progress.setTotal(expectedPostingsCount);
494 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
495 http.setAllowUserInteraction(false);
496 publishProgress(progress);
497 switch (http.getResponseCode()) {
503 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
505 ArrayList<LedgerTransaction> trList = new ArrayList<>();
506 try (InputStream resp = http.getInputStream()) {
509 TransactionListParser parser = TransactionListParser.forApiVersion(apiVersion, resp);
511 int processedPostings = 0;
515 LedgerTransaction transaction = parser.nextTransaction();
517 if (transaction == null)
520 trList.add(transaction);
522 progress.setProgress(processedPostings += transaction.getAccounts()
524 // Logger.debug("trParser",
525 // String.format(Locale.US, "Parsed transaction %d - %s", transaction
527 // transaction.getDescription()));
528 // for (LedgerTransactionAccount acc : transaction.getAccounts()) {
529 // Logger.debug("trParser",
530 // String.format(Locale.US, " %s", acc.getAccountName()));
532 publishProgress(progress);
538 // json interface returns transactions if file order and the rest of the machinery
539 // expects them in reverse chronological order
540 Collections.sort(trList, (o1, o2) -> {
541 int res = o2.getDate()
542 .compareTo(o1.getDate());
545 return Long.compare(o2.getLedgerId(), o1.getLedgerId());
550 @SuppressLint("DefaultLocale")
552 protected Result doInBackground(Void... params) {
553 Data.backgroundTaskStarted();
554 List<LedgerAccount> accounts;
555 List<LedgerTransaction> transactions;
557 accounts = retrieveAccountList();
558 // accounts is null in API-version auto-detection and means
559 // requesting 'html' API version via the JSON classes
560 // this can't work, and the null results in the legacy code below
562 if (accounts == null)
565 transactions = retrieveTransactionList();
567 if (accounts == null || transactions == null) {
568 accounts = new ArrayList<>();
569 transactions = new ArrayList<>();
570 retrieveTransactionListLegacy(accounts, transactions);
573 new AccountAndTransactionListSaver(accounts, transactions).start();
575 Data.lastUpdateDate.postValue(new Date());
577 return new Result(null);
579 catch (MalformedURLException e) {
581 return new Result("Invalid server URL");
583 catch (HTTPException e) {
586 String.format("HTTP error %d: %s", e.getResponseCode(), e.getMessage()));
588 catch (IOException e) {
590 return new Result(e.getLocalizedMessage());
592 catch (RuntimeJsonMappingException e) {
594 return new Result(Result.ERR_JSON_PARSER_ERROR);
596 catch (ParseException e) {
598 return new Result("Network error");
600 catch (OperationCanceledException e) {
602 return new Result("Operation cancelled");
604 catch (ApiNotSupportedException e) {
606 return new Result("Server version not supported");
609 Data.backgroundTaskFinished();
612 public void throwIfCancelled() {
614 throw new OperationCanceledException(null);
616 private enum ParserState {
617 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
618 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
621 public enum ProgressState {STARTING, RUNNING, FINISHED}
623 public static class Progress {
624 private int progress;
626 private ProgressState state = ProgressState.RUNNING;
627 private String error = null;
628 private boolean indeterminate;
630 indeterminate = true;
632 Progress(int progress, int total) {
633 this.indeterminate = false;
634 this.progress = progress;
637 public static Progress indeterminate() {
638 return new Progress();
640 public static Progress finished(String error) {
641 Progress p = new Progress();
642 p.setState(ProgressState.FINISHED);
646 public int getProgress() {
647 ensureState(ProgressState.RUNNING);
650 protected void setProgress(int progress) {
651 this.progress = progress;
652 this.state = ProgressState.RUNNING;
654 public int getTotal() {
655 ensureState(ProgressState.RUNNING);
658 protected void setTotal(int total) {
660 state = ProgressState.RUNNING;
661 indeterminate = total == -1;
663 private void ensureState(ProgressState wanted) {
665 throw new IllegalStateException(
666 String.format("Bad state: %s, expected %s", state, wanted));
668 public ProgressState getState() {
671 public void setState(ProgressState state) {
674 public String getError() {
675 ensureState(ProgressState.FINISHED);
678 public void setError(String error) {
680 state = ProgressState.FINISHED;
682 public boolean isIndeterminate() {
683 return indeterminate;
685 public void setIndeterminate(boolean indeterminate) {
686 this.indeterminate = indeterminate;
690 private static class TransactionParserException extends IllegalStateException {
691 TransactionParserException(String message) {
696 public static class Result {
697 public static String ERR_JSON_PARSER_ERROR = "err_json_parser";
699 public List<LedgerAccount> accounts;
700 public List<LedgerTransaction> transactions;
701 Result(String error) {
704 Result(List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
705 this.accounts = accounts;
706 this.transactions = transactions;
710 private class AccountAndTransactionListSaver extends Thread {
711 private final List<LedgerAccount> accounts;
712 private final List<LedgerTransaction> transactions;
713 public AccountAndTransactionListSaver(List<LedgerAccount> accounts,
714 List<LedgerTransaction> transactions) {
715 this.accounts = accounts;
716 this.transactions = transactions;
720 AccountDAO accDao = DB.get()
722 TransactionDAO trDao = DB.get()
723 .getTransactionDAO();
725 Logger.debug(TAG, "Preparing account list");
726 final List<AccountWithAmounts> list = new ArrayList<>();
727 for (LedgerAccount acc : accounts) {
728 final AccountWithAmounts a = acc.toDBOWithAmounts();
729 Account existing = accDao.getByNameSync(profile.getId(), acc.getName());
730 if (existing != null) {
731 a.account.setExpanded(existing.isExpanded());
732 a.account.setAmountsExpanded(existing.isAmountsExpanded());
733 a.account.setId(existing.getId()); // not strictly needed, but since we have it
739 Logger.debug(TAG, "Account list prepared. Storing");
740 accDao.storeAccountsSync(list, profile.getId());
741 Logger.debug(TAG, "Account list stored");
743 Logger.debug(TAG, "Preparing transaction list");
744 final List<TransactionWithAccounts> tranList = new ArrayList<>();
746 for (LedgerTransaction tr : transactions)
747 tranList.add(tr.toDBO());
749 Logger.debug(TAG, "Storing transaction list");
750 trDao.storeTransactionsSync(tranList, profile.getId());
752 Logger.debug(TAG, "Transactions stored");
756 .insertSync(new Option(profile.getId(), Option.OPT_LAST_SCRAPE,
757 String.valueOf((new Date()).getTime())));