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.database.sqlite.SQLiteDatabase;
22 import android.os.AsyncTask;
23 import android.os.OperationCanceledException;
25 import androidx.annotation.NonNull;
27 import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
29 import net.ktnx.mobileledger.App;
30 import net.ktnx.mobileledger.err.HTTPException;
31 import net.ktnx.mobileledger.json.API;
32 import net.ktnx.mobileledger.json.AccountListParser;
33 import net.ktnx.mobileledger.json.ApiNotSupportedException;
34 import net.ktnx.mobileledger.json.TransactionListParser;
35 import net.ktnx.mobileledger.model.Data;
36 import net.ktnx.mobileledger.model.LedgerAccount;
37 import net.ktnx.mobileledger.model.LedgerTransaction;
38 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
39 import net.ktnx.mobileledger.model.MobileLedgerProfile;
40 import net.ktnx.mobileledger.ui.MainModel;
41 import net.ktnx.mobileledger.utils.Logger;
42 import net.ktnx.mobileledger.utils.NetworkUtil;
44 import java.io.BufferedReader;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
48 import java.net.HttpURLConnection;
49 import java.net.MalformedURLException;
50 import java.net.URLDecoder;
51 import java.nio.charset.StandardCharsets;
52 import java.text.ParseException;
53 import java.util.ArrayList;
54 import java.util.Collections;
55 import java.util.HashMap;
56 import java.util.List;
57 import java.util.Locale;
58 import java.util.Objects;
59 import java.util.regex.Matcher;
60 import java.util.regex.Pattern;
63 public class RetrieveTransactionsTask extends
64 AsyncTask<Void, RetrieveTransactionsTask.Progress, RetrieveTransactionsTask.Result> {
65 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
66 private static final Pattern reComment = Pattern.compile("^\\s*;");
67 private static final Pattern reTransactionStart = Pattern.compile(
68 "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
69 "\"[^\"]*>([\\d.-]+)</td>");
70 private static final Pattern reTransactionDescription =
71 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
72 private static final Pattern reTransactionDetails = Pattern.compile(
73 "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
74 "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
75 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
76 private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
77 private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
79 private final Pattern reAccountName =
80 Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
81 private final Pattern reAccountValue = Pattern.compile(
82 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
83 private final MainModel mainModel;
84 private final MobileLedgerProfile profile;
85 private final List<LedgerAccount> prevAccounts;
86 private int expectedPostingsCount = -1;
87 public RetrieveTransactionsTask(@NonNull MainModel mainModel,
88 @NonNull MobileLedgerProfile profile,
89 List<LedgerAccount> accounts) {
90 this.mainModel = mainModel;
91 this.profile = profile;
92 this.prevAccounts = accounts;
94 private static void L(String msg) {
95 //debug("transaction-parser", msg);
97 static LedgerTransactionAccount parseTransactionAccountLine(String line) {
98 Matcher m = reTransactionDetails.matcher(line);
100 String postingStatus = m.group(1);
101 String acc_name = m.group(2);
102 String currencyPre = m.group(3);
103 String amount = Objects.requireNonNull(m.group(4));
104 String currencyPost = m.group(5);
106 String currency = null;
107 if ((currencyPre != null) && (currencyPre.length() > 0)) {
108 if ((currencyPost != null) && (currencyPost.length() > 0))
110 currency = currencyPre;
112 else if ((currencyPost != null) && (currencyPost.length() > 0)) {
113 currency = currencyPost;
116 amount = amount.replace(',', '.');
118 return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
125 protected void onProgressUpdate(Progress... values) {
126 super.onProgressUpdate(values);
127 Data.backgroundTaskProgress.postValue(values[0]);
130 protected void onPostExecute(Result result) {
131 super.onPostExecute(result);
132 Progress progress = new Progress();
133 progress.setState(ProgressState.FINISHED);
134 progress.setError(result.error);
135 onProgressUpdate(progress);
138 protected void onCancelled() {
140 Progress progress = new Progress();
141 progress.setState(ProgressState.FINISHED);
142 onProgressUpdate(progress);
144 private void retrieveTransactionListLegacy(List<LedgerAccount> accounts,
145 List<LedgerTransaction> transactions)
146 throws IOException, HTTPException {
147 Progress progress = Progress.indeterminate();
148 progress.setState(ProgressState.RUNNING);
149 progress.setTotal(expectedPostingsCount);
150 int maxTransactionId = -1;
151 HashMap<String, LedgerAccount> map = new HashMap<>();
152 LedgerAccount lastAccount = null;
153 ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
155 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
156 http.setAllowUserInteraction(false);
157 publishProgress(progress);
158 if (http.getResponseCode() != 200)
159 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
161 try (InputStream resp = http.getInputStream()) {
162 if (http.getResponseCode() != 200)
163 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
165 int matchedTransactionsCount = 0;
167 ParserState state = ParserState.EXPECTING_ACCOUNT;
170 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
172 int processedTransactionCount = 0;
173 int transactionId = 0;
174 LedgerTransaction transaction = null;
176 while ((line = buf.readLine()) != null) {
179 m = reComment.matcher(line);
181 // TODO: comments are ignored for now
182 // Log.v("transaction-parser", "Ignoring comment");
185 //L(String.format("State is %d", updating));
187 case EXPECTING_ACCOUNT:
188 if (line.equals("<h2>General Journal</h2>")) {
189 state = ParserState.EXPECTING_TRANSACTION;
190 L("→ expecting transaction");
193 m = reAccountName.matcher(line);
195 String acct_encoded = m.group(1);
196 String accName = URLDecoder.decode(acct_encoded, "UTF-8");
197 accName = accName.replace("\"", "");
198 L(String.format("found account: %s", accName));
200 lastAccount = map.get(accName);
201 if (lastAccount != null) {
202 L(String.format("ignoring duplicate account '%s'", accName));
205 String parentAccountName = LedgerAccount.extractParentName(accName);
206 LedgerAccount parentAccount;
207 if (parentAccountName != null) {
208 parentAccount = ensureAccountExists(parentAccountName, map,
212 parentAccount = null;
214 lastAccount = new LedgerAccount(accName, parentAccount);
216 accounts.add(lastAccount);
217 map.put(accName, lastAccount);
219 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
220 L("→ expecting account amount");
224 case EXPECTING_ACCOUNT_AMOUNT:
225 m = reAccountValue.matcher(line);
226 boolean match_found = false;
231 String value = Objects.requireNonNull(m.group(1));
232 String currency = m.group(2);
233 if (currency == null)
237 Matcher tmpM = reDecimalComma.matcher(value);
239 value = value.replace(".", "");
240 value = value.replace(',', '.');
243 tmpM = reDecimalPoint.matcher(value);
245 value = value.replace(",", "");
246 value = value.replace(" ", "");
249 L("curr=" + currency + ", value=" + value);
250 final float val = Float.parseFloat(value);
251 lastAccount.addAmount(val, currency);
252 for (LedgerAccount syn : syntheticAccounts) {
253 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
254 currency, val, syn.getName()));
255 syn.addAmount(val, currency);
260 syntheticAccounts.clear();
261 state = ParserState.EXPECTING_ACCOUNT;
262 L("→ expecting account");
267 case EXPECTING_TRANSACTION:
268 if (!line.isEmpty() && (line.charAt(0) == ' '))
270 m = reTransactionStart.matcher(line);
272 transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
273 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
274 L(String.format(Locale.ENGLISH,
275 "found transaction %d → expecting description", transactionId));
276 progress.setProgress(++processedTransactionCount);
277 if (maxTransactionId < transactionId)
278 maxTransactionId = transactionId;
279 if ((progress.isIndeterminate()) ||
280 (progress.getTotal() < transactionId))
281 progress.setTotal(transactionId);
282 publishProgress(progress);
284 m = reEnd.matcher(line);
286 L("--- transaction value complete ---");
291 case EXPECTING_TRANSACTION_DESCRIPTION:
292 if (!line.isEmpty() && (line.charAt(0) == ' '))
294 m = reTransactionDescription.matcher(line);
296 if (transactionId == 0)
297 throw new TransactionParserException(
298 "Transaction Id is 0 while expecting description");
300 String date = Objects.requireNonNull(m.group(1));
302 int equalsIndex = date.indexOf('=');
303 if (equalsIndex >= 0)
304 date = date.substring(equalsIndex + 1);
306 new LedgerTransaction(transactionId, date, m.group(2));
308 catch (ParseException e) {
309 throw new TransactionParserException(
310 String.format("Error parsing date '%s'", date));
312 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
313 L(String.format(Locale.ENGLISH,
314 "transaction %d created for %s (%s) →" + " expecting details",
315 transactionId, date, m.group(2)));
319 case EXPECTING_TRANSACTION_DETAILS:
320 if (line.isEmpty()) {
321 // transaction data collected
323 transaction.finishLoading();
324 transactions.add(transaction);
326 state = ParserState.EXPECTING_TRANSACTION;
327 L(String.format("transaction %s parsed → expecting transaction",
328 transaction.getId()));
330 // sounds like a good idea, but transaction-1 may not be the first one chronologically
331 // for example, when you add the initial seeding transaction after entering some others
332 // if (transactionId == 1) {
333 // L("This was the initial transaction.
340 LedgerTransactionAccount lta = parseTransactionAccountLine(line);
342 transaction.addAccount(lta);
343 L(String.format(Locale.ENGLISH, "%d: %s = %s", transaction.getId(),
344 lta.getAccountName(), lta.getAmount()));
347 throw new IllegalStateException(
348 String.format("Can't parse transaction %d details: %s",
349 transactionId, line));
353 throw new RuntimeException(
354 String.format("Unknown parser updating %s", state.name()));
362 public LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
363 ArrayList<LedgerAccount> createdAccounts) {
364 LedgerAccount acc = map.get(accountName);
369 String parentName = LedgerAccount.extractParentName(accountName);
370 LedgerAccount parentAccount;
371 if (parentName != null) {
372 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
375 parentAccount = null;
378 acc = new LedgerAccount(accountName, parentAccount);
379 createdAccounts.add(acc);
382 public void addNumberOfPostings(int number) {
383 expectedPostingsCount += number;
385 private List<LedgerAccount> retrieveAccountList()
386 throws IOException, HTTPException, ApiNotSupportedException {
387 final API apiVersion = profile.getApiVersion();
388 if (apiVersion.equals(API.auto)) {
389 return retrieveAccountListAnyVersion();
391 else if (apiVersion.equals(API.html)) {
393 "Declining using JSON API for /accounts with configured legacy API version");
397 return retrieveAccountListForVersion(apiVersion);
400 private List<LedgerAccount> retrieveAccountListAnyVersion()
401 throws HTTPException, ApiNotSupportedException {
402 for (API ver : API.allVersions) {
404 return retrieveAccountListForVersion(ver);
406 catch (Exception e) {
408 String.format(Locale.US, "Error during account list retrieval using API %s",
409 ver.getDescription()));
412 throw new ApiNotSupportedException();
415 throw new RuntimeException("This should never be reached");
417 private List<LedgerAccount> retrieveAccountListForVersion(API version)
418 throws IOException, HTTPException {
419 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
420 http.setAllowUserInteraction(false);
421 switch (http.getResponseCode()) {
427 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
429 publishProgress(Progress.indeterminate());
430 SQLiteDatabase db = App.getDatabase();
431 ArrayList<LedgerAccount> list = new ArrayList<>();
432 HashMap<String, LedgerAccount> map = new HashMap<>();
433 HashMap<String, LedgerAccount> currentMap = new HashMap<>();
434 for (LedgerAccount acc : prevAccounts)
435 currentMap.put(acc.getName(), acc);
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);
455 // the current account tree may have changed, update the new-to be tree to match
456 for (LedgerAccount acc : list) {
457 LedgerAccount prevData = currentMap.get(acc.getName());
458 if (prevData != null) {
459 acc.setExpanded(prevData.isExpanded());
460 acc.setAmountsExpanded(prevData.amountsExpanded());
466 private List<LedgerTransaction> retrieveTransactionList()
467 throws ParseException, HTTPException, IOException, ApiNotSupportedException {
468 final API apiVersion = profile.getApiVersion();
469 if (apiVersion.equals(API.auto)) {
470 return retrieveTransactionListAnyVersion();
472 else if (apiVersion.equals(API.html)) {
474 "Declining using JSON API for /accounts with configured legacy API version");
478 return retrieveTransactionListForVersion(apiVersion);
482 private List<LedgerTransaction> retrieveTransactionListAnyVersion()
483 throws ApiNotSupportedException {
484 for (API ver : API.allVersions) {
486 return retrieveTransactionListForVersion(ver);
488 catch (Exception | HTTPException e) {
490 String.format(Locale.US, "Error during account list retrieval using API %s",
491 ver.getDescription()));
494 throw new ApiNotSupportedException();
497 throw new RuntimeException("This should never be reached");
499 private List<LedgerTransaction> retrieveTransactionListForVersion(API apiVersion)
500 throws IOException, ParseException, HTTPException {
501 Progress progress = new Progress();
502 progress.setTotal(expectedPostingsCount);
504 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
505 http.setAllowUserInteraction(false);
506 publishProgress(progress);
507 switch (http.getResponseCode()) {
513 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
515 ArrayList<LedgerTransaction> trList = new ArrayList<>();
516 try (InputStream resp = http.getInputStream()) {
519 TransactionListParser parser = TransactionListParser.forApiVersion(apiVersion, resp);
521 int processedPostings = 0;
525 LedgerTransaction transaction = parser.nextTransaction();
527 if (transaction == null)
530 trList.add(transaction);
532 progress.setProgress(processedPostings += transaction.getAccounts()
534 // Logger.debug("trParser",
535 // String.format(Locale.US, "Parsed transaction %d - %s", transaction
537 // transaction.getDescription()));
538 // for (LedgerTransactionAccount acc : transaction.getAccounts()) {
539 // Logger.debug("trParser",
540 // String.format(Locale.US, " %s", acc.getAccountName()));
542 publishProgress(progress);
548 // json interface returns transactions if file order and the rest of the machinery
549 // expects them in reverse chronological order
550 Collections.sort(trList, (o1, o2) -> {
551 int res = o2.getDate()
552 .compareTo(o1.getDate());
555 return Long.compare(o2.getId(), o1.getId());
560 @SuppressLint("DefaultLocale")
562 protected Result doInBackground(Void... params) {
563 Data.backgroundTaskStarted();
564 List<LedgerAccount> accounts;
565 List<LedgerTransaction> transactions;
567 accounts = retrieveAccountList();
568 // accounts is null in API-version auto-detection and means
569 // requesting 'html' API version via the JSON classes
570 // this can't work, and the null results in the legacy code below
572 if (accounts == null)
575 transactions = retrieveTransactionList();
577 if (accounts == null || transactions == null) {
578 accounts = new ArrayList<>();
579 transactions = new ArrayList<>();
580 retrieveTransactionListLegacy(accounts, transactions);
582 mainModel.setAndStoreAccountAndTransactionListFromWeb(accounts, transactions);
584 return new Result(accounts, transactions);
586 catch (MalformedURLException e) {
588 return new Result("Invalid server URL");
590 catch (HTTPException e) {
592 return new Result(String.format("HTTP error %d: %s", e.getResponseCode(),
593 e.getResponseMessage()));
595 catch (IOException e) {
597 return new Result(e.getLocalizedMessage());
599 catch (RuntimeJsonMappingException e) {
601 return new Result(Result.ERR_JSON_PARSER_ERROR);
603 catch (ParseException e) {
605 return new Result("Network error");
607 catch (OperationCanceledException e) {
609 return new Result("Operation cancelled");
611 catch (ApiNotSupportedException e) {
613 return new Result("Server version not supported");
616 Data.backgroundTaskFinished();
619 public void throwIfCancelled() {
621 throw new OperationCanceledException(null);
623 private enum ParserState {
624 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
625 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
628 public enum ProgressState {STARTING, RUNNING, FINISHED}
630 public static class Progress {
631 private int progress;
633 private ProgressState state = ProgressState.RUNNING;
634 private String error = null;
635 private boolean indeterminate;
637 indeterminate = true;
639 Progress(int progress, int total) {
640 this.indeterminate = false;
641 this.progress = progress;
644 public static Progress indeterminate() {
645 return new Progress();
647 public static Progress finished(String error) {
648 Progress p = new Progress();
649 p.setState(ProgressState.FINISHED);
653 public int getProgress() {
654 ensureState(ProgressState.RUNNING);
657 protected void setProgress(int progress) {
658 this.progress = progress;
659 this.state = ProgressState.RUNNING;
661 public int getTotal() {
662 ensureState(ProgressState.RUNNING);
665 protected void setTotal(int total) {
667 state = ProgressState.RUNNING;
668 indeterminate = total == -1;
670 private void ensureState(ProgressState wanted) {
672 throw new IllegalStateException(
673 String.format("Bad state: %s, expected %s", state, wanted));
675 public ProgressState getState() {
678 public void setState(ProgressState state) {
681 public String getError() {
682 ensureState(ProgressState.FINISHED);
685 public void setError(String error) {
687 state = ProgressState.FINISHED;
689 public boolean isIndeterminate() {
690 return indeterminate;
692 public void setIndeterminate(boolean indeterminate) {
693 this.indeterminate = indeterminate;
697 private static class TransactionParserException extends IllegalStateException {
698 TransactionParserException(String message) {
703 public static class Result {
704 public static String ERR_JSON_PARSER_ERROR = "err_json_parser";
706 public List<LedgerAccount> accounts;
707 public List<LedgerTransaction> transactions;
708 Result(String error) {
711 Result(List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
712 this.accounts = accounts;
713 this.transactions = transactions;