2 * Copyright © 2020 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.AccountListParser;
32 import net.ktnx.mobileledger.json.ApiNotSupportedException;
33 import net.ktnx.mobileledger.json.TransactionListParser;
34 import net.ktnx.mobileledger.model.Data;
35 import net.ktnx.mobileledger.model.LedgerAccount;
36 import net.ktnx.mobileledger.model.LedgerTransaction;
37 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
38 import net.ktnx.mobileledger.model.MobileLedgerProfile;
39 import net.ktnx.mobileledger.ui.MainModel;
40 import net.ktnx.mobileledger.utils.Logger;
41 import net.ktnx.mobileledger.utils.NetworkUtil;
43 import java.io.BufferedReader;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.io.InputStreamReader;
47 import java.net.HttpURLConnection;
48 import java.net.MalformedURLException;
49 import java.net.URLDecoder;
50 import java.nio.charset.StandardCharsets;
51 import java.text.ParseException;
52 import java.util.ArrayList;
53 import java.util.Collections;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Locale;
57 import java.util.Objects;
58 import java.util.regex.Matcher;
59 import java.util.regex.Pattern;
62 public class RetrieveTransactionsTask extends
63 AsyncTask<Void, RetrieveTransactionsTask.Progress, RetrieveTransactionsTask.Result> {
64 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
65 private static final Pattern reComment = Pattern.compile("^\\s*;");
66 private static final Pattern reTransactionStart = Pattern.compile(
67 "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
68 "\"[^\"]*>([\\d.-]+)</td>");
69 private static final Pattern reTransactionDescription =
70 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
71 private static final Pattern reTransactionDetails = Pattern.compile(
72 "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
73 "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
74 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
75 private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
76 private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
78 private final Pattern reAccountName =
79 Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
80 private final Pattern reAccountValue = Pattern.compile(
81 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
82 private final MainModel mainModel;
83 private final MobileLedgerProfile profile;
84 private final List<LedgerAccount> prevAccounts;
85 private int expectedPostingsCount = -1;
86 public RetrieveTransactionsTask(@NonNull MainModel mainModel,
87 @NonNull MobileLedgerProfile profile,
88 List<LedgerAccount> accounts) {
89 this.mainModel = mainModel;
90 this.profile = profile;
91 this.prevAccounts = accounts;
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 public MobileLedgerProfile getProfile() {
127 protected void onProgressUpdate(Progress... values) {
128 super.onProgressUpdate(values);
129 Data.backgroundTaskProgress.postValue(values[0]);
132 protected void onPostExecute(Result result) {
133 super.onPostExecute(result);
134 Progress progress = new Progress();
135 progress.setState(ProgressState.FINISHED);
136 progress.setError(result.error);
137 onProgressUpdate(progress);
140 protected void onCancelled() {
142 Progress progress = new Progress();
143 progress.setState(ProgressState.FINISHED);
144 onProgressUpdate(progress);
146 private void retrieveTransactionListLegacy(List<LedgerAccount> accounts,
147 List<LedgerTransaction> transactions)
148 throws IOException, HTTPException {
149 Progress progress = Progress.indeterminate();
150 progress.setState(ProgressState.RUNNING);
151 progress.setTotal(expectedPostingsCount);
152 int maxTransactionId = -1;
153 HashMap<String, LedgerAccount> map = new HashMap<>();
154 LedgerAccount lastAccount = null;
155 ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
157 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
158 http.setAllowUserInteraction(false);
159 publishProgress(progress);
160 if (http.getResponseCode() != 200)
161 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
163 try (InputStream resp = http.getInputStream()) {
164 if (http.getResponseCode() != 200)
165 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
167 int matchedTransactionsCount = 0;
169 ParserState state = ParserState.EXPECTING_ACCOUNT;
172 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
174 int processedTransactionCount = 0;
175 int transactionId = 0;
176 LedgerTransaction transaction = null;
178 while ((line = buf.readLine()) != null) {
181 m = reComment.matcher(line);
183 // TODO: comments are ignored for now
184 // Log.v("transaction-parser", "Ignoring comment");
187 //L(String.format("State is %d", updating));
189 case EXPECTING_ACCOUNT:
190 if (line.equals("<h2>General Journal</h2>")) {
191 state = ParserState.EXPECTING_TRANSACTION;
192 L("→ expecting transaction");
195 m = reAccountName.matcher(line);
197 String acct_encoded = m.group(1);
198 String accName = URLDecoder.decode(acct_encoded, "UTF-8");
199 accName = accName.replace("\"", "");
200 L(String.format("found account: %s", accName));
202 lastAccount = map.get(accName);
203 if (lastAccount != null) {
204 L(String.format("ignoring duplicate account '%s'", accName));
207 String parentAccountName = LedgerAccount.extractParentName(accName);
208 LedgerAccount parentAccount;
209 if (parentAccountName != null) {
210 parentAccount = ensureAccountExists(parentAccountName, map,
214 parentAccount = null;
216 lastAccount = new LedgerAccount(profile, accName, parentAccount);
218 accounts.add(lastAccount);
219 map.put(accName, lastAccount);
221 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
222 L("→ expecting account amount");
226 case EXPECTING_ACCOUNT_AMOUNT:
227 m = reAccountValue.matcher(line);
228 boolean match_found = false;
233 String value = Objects.requireNonNull(m.group(1));
234 String currency = m.group(2);
235 if (currency == null)
239 Matcher tmpM = reDecimalComma.matcher(value);
241 value = value.replace(".", "");
242 value = value.replace(',', '.');
245 tmpM = reDecimalPoint.matcher(value);
247 value = value.replace(",", "");
248 value = value.replace(" ", "");
251 L("curr=" + currency + ", value=" + value);
252 final float val = Float.parseFloat(value);
253 lastAccount.addAmount(val, currency);
254 for (LedgerAccount syn : syntheticAccounts) {
255 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
256 currency, val, syn.getName()));
257 syn.addAmount(val, currency);
262 syntheticAccounts.clear();
263 state = ParserState.EXPECTING_ACCOUNT;
264 L("→ expecting account");
269 case EXPECTING_TRANSACTION:
270 if (!line.isEmpty() && (line.charAt(0) == ' '))
272 m = reTransactionStart.matcher(line);
274 transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
275 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
276 L(String.format(Locale.ENGLISH,
277 "found transaction %d → expecting description", transactionId));
278 progress.setProgress(++processedTransactionCount);
279 if (maxTransactionId < transactionId)
280 maxTransactionId = transactionId;
281 if ((progress.isIndeterminate()) ||
282 (progress.getTotal() < transactionId))
283 progress.setTotal(transactionId);
284 publishProgress(progress);
286 m = reEnd.matcher(line);
288 L("--- transaction value complete ---");
293 case EXPECTING_TRANSACTION_DESCRIPTION:
294 if (!line.isEmpty() && (line.charAt(0) == ' '))
296 m = reTransactionDescription.matcher(line);
298 if (transactionId == 0)
299 throw new TransactionParserException(
300 "Transaction Id is 0 while expecting description");
302 String date = Objects.requireNonNull(m.group(1));
304 int equalsIndex = date.indexOf('=');
305 if (equalsIndex >= 0)
306 date = date.substring(equalsIndex + 1);
308 new LedgerTransaction(transactionId, date, m.group(2));
310 catch (ParseException e) {
311 throw new TransactionParserException(
312 String.format("Error parsing date '%s'", date));
314 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
315 L(String.format(Locale.ENGLISH,
316 "transaction %d created for %s (%s) →" + " expecting details",
317 transactionId, date, m.group(2)));
321 case EXPECTING_TRANSACTION_DETAILS:
322 if (line.isEmpty()) {
323 // transaction data collected
325 transaction.finishLoading();
326 transactions.add(transaction);
328 state = ParserState.EXPECTING_TRANSACTION;
329 L(String.format("transaction %s parsed → expecting transaction",
330 transaction.getId()));
332 // sounds like a good idea, but transaction-1 may not be the first one chronologically
333 // for example, when you add the initial seeding transaction after entering some others
334 // if (transactionId == 1) {
335 // L("This was the initial transaction.
342 LedgerTransactionAccount lta = parseTransactionAccountLine(line);
344 transaction.addAccount(lta);
345 L(String.format(Locale.ENGLISH, "%d: %s = %s", transaction.getId(),
346 lta.getAccountName(), lta.getAmount()));
349 throw new IllegalStateException(
350 String.format("Can't parse transaction %d details: %s",
351 transactionId, line));
355 throw new RuntimeException(
356 String.format("Unknown parser updating %s", state.name()));
364 public LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
365 ArrayList<LedgerAccount> createdAccounts) {
366 LedgerAccount acc = map.get(accountName);
371 String parentName = LedgerAccount.extractParentName(accountName);
372 LedgerAccount parentAccount;
373 if (parentName != null) {
374 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
377 parentAccount = null;
380 acc = new LedgerAccount(profile, accountName, parentAccount);
381 createdAccounts.add(acc);
384 public void addNumberOfPostings(int number) {
385 expectedPostingsCount += number;
387 private List<LedgerAccount> retrieveAccountList()
388 throws IOException, HTTPException, ApiNotSupportedException {
389 final SendTransactionTask.API apiVersion = profile.getApiVersion();
390 if (apiVersion.equals(SendTransactionTask.API.auto)) {
391 return retrieveAccountListAnyVersion();
393 else if (apiVersion.equals(SendTransactionTask.API.html)) {
395 "Declining using JSON API for /accounts with configured legacy API version");
399 return retrieveAccountListForVersion(apiVersion);
402 private List<LedgerAccount> retrieveAccountListAnyVersion()
403 throws HTTPException, ApiNotSupportedException {
404 for (SendTransactionTask.API ver : SendTransactionTask.API.allVersions) {
406 return retrieveAccountListForVersion(ver);
408 catch (Exception e) {
410 String.format(Locale.US, "Error during account list retrieval using API %s",
411 ver.getDescription()));
414 throw new ApiNotSupportedException();
417 throw new RuntimeException("This should never be reached");
419 private List<LedgerAccount> retrieveAccountListForVersion(SendTransactionTask.API version)
420 throws IOException, HTTPException {
421 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
422 http.setAllowUserInteraction(false);
423 switch (http.getResponseCode()) {
429 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
431 publishProgress(Progress.indeterminate());
432 SQLiteDatabase db = App.getDatabase();
433 ArrayList<LedgerAccount> list = new ArrayList<>();
434 HashMap<String, LedgerAccount> map = new HashMap<>();
435 HashMap<String, LedgerAccount> currentMap = new HashMap<>();
436 for (LedgerAccount acc : prevAccounts)
437 currentMap.put(acc.getName(), acc);
439 try (InputStream resp = http.getInputStream()) {
441 if (http.getResponseCode() != 200)
442 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
444 AccountListParser parser = AccountListParser.forApiVersion(version, resp);
445 expectedPostingsCount = 0;
449 LedgerAccount acc = parser.nextAccount(this, map);
457 // the current account tree may have changed, update the new-to be tree to match
458 for (LedgerAccount acc : list) {
459 LedgerAccount prevData = currentMap.get(acc.getName());
460 if (prevData != null) {
461 acc.setExpanded(prevData.isExpanded());
462 acc.setAmountsExpanded(prevData.amountsExpanded());
468 private List<LedgerTransaction> retrieveTransactionList()
469 throws ParseException, HTTPException, IOException, ApiNotSupportedException {
470 final SendTransactionTask.API apiVersion = profile.getApiVersion();
471 if (apiVersion.equals(SendTransactionTask.API.auto)) {
472 return retrieveTransactionListAnyVersion();
474 else if (apiVersion.equals(SendTransactionTask.API.html)) {
476 "Declining using JSON API for /accounts with configured legacy API version");
480 return retrieveTransactionListForVersion(apiVersion);
484 private List<LedgerTransaction> retrieveTransactionListAnyVersion()
485 throws ApiNotSupportedException {
486 for (SendTransactionTask.API ver : SendTransactionTask.API.allVersions) {
488 return retrieveTransactionListForVersion(ver);
490 catch (Exception | HTTPException e) {
492 String.format(Locale.US, "Error during account list retrieval using API %s",
493 ver.getDescription()));
496 throw new ApiNotSupportedException();
499 throw new RuntimeException("This should never be reached");
501 private List<LedgerTransaction> retrieveTransactionListForVersion(
502 SendTransactionTask.API apiVersion) throws IOException, ParseException, HTTPException {
503 Progress progress = new Progress();
504 progress.setTotal(expectedPostingsCount);
506 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
507 http.setAllowUserInteraction(false);
508 publishProgress(progress);
509 switch (http.getResponseCode()) {
515 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
517 ArrayList<LedgerTransaction> trList = new ArrayList<>();
518 try (InputStream resp = http.getInputStream()) {
521 TransactionListParser parser = TransactionListParser.forApiVersion(apiVersion, resp);
523 int processedPostings = 0;
527 LedgerTransaction transaction = parser.nextTransaction();
529 if (transaction == null)
532 trList.add(transaction);
534 progress.setProgress(processedPostings += transaction.getAccounts()
536 // Logger.debug("trParser",
537 // String.format(Locale.US, "Parsed transaction %d - %s", transaction
539 // transaction.getDescription()));
540 // for (LedgerTransactionAccount acc : transaction.getAccounts()) {
541 // Logger.debug("trParser",
542 // String.format(Locale.US, " %s", acc.getAccountName()));
544 publishProgress(progress);
550 // json interface returns transactions if file order and the rest of the machinery
551 // expects them in reverse chronological order
552 Collections.sort(trList, (o1, o2) -> {
553 int res = o2.getDate()
554 .compareTo(o1.getDate());
557 return Integer.compare(o2.getId(), o1.getId());
562 @SuppressLint("DefaultLocale")
564 protected Result doInBackground(Void... params) {
565 Data.backgroundTaskStarted();
566 List<LedgerAccount> accounts;
567 List<LedgerTransaction> transactions;
569 accounts = retrieveAccountList();
570 // accounts is null in API-version auto-detection and means
571 // requesting 'html' API version via the JSON classes
572 // this can't work, and the null results in the legacy code below
574 if (accounts == null)
577 transactions = retrieveTransactionList();
579 if (accounts == null || transactions == null) {
580 accounts = new ArrayList<>();
581 transactions = new ArrayList<>();
582 retrieveTransactionListLegacy(accounts, transactions);
584 mainModel.setAndStoreAccountAndTransactionListFromWeb(accounts, transactions);
586 return new Result(accounts, transactions);
588 catch (MalformedURLException e) {
590 return new Result("Invalid server URL");
592 catch (HTTPException e) {
594 return new Result(String.format("HTTP error %d: %s", e.getResponseCode(),
595 e.getResponseMessage()));
597 catch (IOException e) {
599 return new Result(e.getLocalizedMessage());
601 catch (RuntimeJsonMappingException e) {
603 return new Result(Result.ERR_JSON_PARSER_ERROR);
605 catch (ParseException e) {
607 return new Result("Network error");
609 catch (OperationCanceledException e) {
611 return new Result("Operation cancelled");
613 catch (ApiNotSupportedException e) {
615 return new Result("Server version not supported");
618 Data.backgroundTaskFinished();
621 public void throwIfCancelled() {
623 throw new OperationCanceledException(null);
625 private enum ParserState {
626 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
627 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
630 public enum ProgressState {STARTING, RUNNING, FINISHED}
632 public static class Progress {
633 private int progress;
635 private ProgressState state = ProgressState.RUNNING;
636 private String error = null;
637 private boolean indeterminate;
639 indeterminate = true;
641 Progress(int progress, int total) {
642 this.indeterminate = false;
643 this.progress = progress;
646 public static Progress indeterminate() {
647 return new Progress();
649 public static Progress finished(String error) {
650 Progress p = new Progress();
651 p.setState(ProgressState.FINISHED);
655 public int getProgress() {
656 ensureState(ProgressState.RUNNING);
659 protected void setProgress(int progress) {
660 this.progress = progress;
661 this.state = ProgressState.RUNNING;
663 public int getTotal() {
664 ensureState(ProgressState.RUNNING);
667 protected void setTotal(int total) {
669 state = ProgressState.RUNNING;
670 indeterminate = total == -1;
672 private void ensureState(ProgressState wanted) {
674 throw new IllegalStateException(
675 String.format("Bad state: %s, expected %s", state, wanted));
677 public ProgressState getState() {
680 public void setState(ProgressState state) {
683 public String getError() {
684 ensureState(ProgressState.FINISHED);
687 public void setError(String error) {
689 state = ProgressState.FINISHED;
691 public boolean isIndeterminate() {
692 return indeterminate;
694 public void setIndeterminate(boolean indeterminate) {
695 this.indeterminate = indeterminate;
699 private static class TransactionParserException extends IllegalStateException {
700 TransactionParserException(String message) {
705 public static class Result {
706 public static String ERR_JSON_PARSER_ERROR = "err_json_parser";
708 public List<LedgerAccount> accounts;
709 public List<LedgerTransaction> transactions;
710 Result(String error) {
713 Result(List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
714 this.accounts = accounts;
715 this.transactions = transactions;