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 net.ktnx.mobileledger.App;
28 import net.ktnx.mobileledger.err.HTTPException;
29 import net.ktnx.mobileledger.json.v1_15.AccountListParser;
30 import net.ktnx.mobileledger.json.v1_15.ParsedBalance;
31 import net.ktnx.mobileledger.json.v1_15.ParsedLedgerAccount;
32 import net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction;
33 import net.ktnx.mobileledger.json.v1_15.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.NetworkUtil;
42 import java.io.BufferedReader;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.InputStreamReader;
46 import java.net.HttpURLConnection;
47 import java.net.MalformedURLException;
48 import java.net.URLDecoder;
49 import java.nio.charset.StandardCharsets;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.Collections;
53 import java.util.HashMap;
54 import java.util.List;
55 import java.util.Locale;
56 import java.util.Objects;
57 import java.util.regex.Matcher;
58 import java.util.regex.Pattern;
61 public class RetrieveTransactionsTask extends
62 AsyncTask<Void, RetrieveTransactionsTask.Progress, RetrieveTransactionsTask.Result> {
63 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
64 private static final Pattern reComment = Pattern.compile("^\\s*;");
65 private static final Pattern reTransactionStart = Pattern.compile(
66 "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
67 "\"[^\"]*>([\\d.-]+)</td>");
68 private static final Pattern reTransactionDescription =
69 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
70 private static final Pattern reTransactionDetails = Pattern.compile(
71 "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
72 "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
73 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
74 private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
75 private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
77 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
78 private Pattern reAccountValue = Pattern.compile(
79 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
80 private MainModel mainModel;
81 private MobileLedgerProfile profile;
82 private List<LedgerAccount> prevAccounts;
83 private int expectedPostingsCount = -1;
84 public RetrieveTransactionsTask(@NonNull MainModel mainModel,
85 @NonNull MobileLedgerProfile profile,
86 List<LedgerAccount> accounts) {
87 this.mainModel = mainModel;
88 this.profile = profile;
89 this.prevAccounts = accounts;
91 private static void L(String msg) {
92 //debug("transaction-parser", msg);
94 static LedgerTransactionAccount parseTransactionAccountLine(String line) {
95 Matcher m = reTransactionDetails.matcher(line);
97 String postingStatus = m.group(1);
98 String acc_name = m.group(2);
99 String currencyPre = m.group(3);
100 String amount = Objects.requireNonNull(m.group(4));
101 String currencyPost = m.group(5);
103 String currency = null;
104 if ((currencyPre != null) && (currencyPre.length() > 0)) {
105 if ((currencyPost != null) && (currencyPost.length() > 0))
107 currency = currencyPre;
109 else if ((currencyPost != null) && (currencyPost.length() > 0)) {
110 currency = currencyPost;
113 amount = amount.replace(',', '.');
115 return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
122 protected void onProgressUpdate(Progress... values) {
123 super.onProgressUpdate(values);
124 Data.backgroundTaskProgress.postValue(values[0]);
127 protected void onPostExecute(Result result) {
128 super.onPostExecute(result);
129 Progress progress = new Progress();
130 progress.setState(ProgressState.FINISHED);
131 progress.setError(result.error);
132 onProgressUpdate(progress);
135 protected void onCancelled() {
137 Progress progress = new Progress();
138 progress.setState(ProgressState.FINISHED);
139 onProgressUpdate(progress);
141 private void retrieveTransactionListLegacy(List<LedgerAccount> accounts,
142 List<LedgerTransaction> transactions)
143 throws IOException, HTTPException {
144 Progress progress = Progress.indeterminate();
145 progress.setState(ProgressState.RUNNING);
146 progress.setTotal(expectedPostingsCount);
147 int maxTransactionId = -1;
148 HashMap<String, LedgerAccount> map = new HashMap<>();
149 LedgerAccount lastAccount = null;
150 ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
152 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
153 http.setAllowUserInteraction(false);
154 publishProgress(progress);
155 if (http.getResponseCode() != 200)
156 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
158 try (InputStream resp = http.getInputStream()) {
159 if (http.getResponseCode() != 200)
160 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
162 int matchedTransactionsCount = 0;
164 ParserState state = ParserState.EXPECTING_ACCOUNT;
167 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
169 int processedTransactionCount = 0;
170 int transactionId = 0;
171 LedgerTransaction transaction = null;
173 while ((line = buf.readLine()) != null) {
176 m = reComment.matcher(line);
178 // TODO: comments are ignored for now
179 // Log.v("transaction-parser", "Ignoring comment");
182 //L(String.format("State is %d", updating));
184 case EXPECTING_ACCOUNT:
185 if (line.equals("<h2>General Journal</h2>")) {
186 state = ParserState.EXPECTING_TRANSACTION;
187 L("→ expecting transaction");
190 m = reAccountName.matcher(line);
192 String acct_encoded = m.group(1);
193 String accName = URLDecoder.decode(acct_encoded, "UTF-8");
194 accName = accName.replace("\"", "");
195 L(String.format("found account: %s", accName));
197 lastAccount = map.get(accName);
198 if (lastAccount != null) {
199 L(String.format("ignoring duplicate account '%s'", accName));
202 String parentAccountName = LedgerAccount.extractParentName(accName);
203 LedgerAccount parentAccount;
204 if (parentAccountName != null) {
205 parentAccount = ensureAccountExists(parentAccountName, map,
209 parentAccount = null;
211 lastAccount = new LedgerAccount(profile, accName, parentAccount);
213 accounts.add(lastAccount);
214 map.put(accName, lastAccount);
216 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
217 L("→ expecting account amount");
221 case EXPECTING_ACCOUNT_AMOUNT:
222 m = reAccountValue.matcher(line);
223 boolean match_found = false;
228 String value = Objects.requireNonNull(m.group(1));
229 String currency = m.group(2);
230 if (currency == null)
234 Matcher tmpM = reDecimalComma.matcher(value);
236 value = value.replace(".", "");
237 value = value.replace(',', '.');
240 tmpM = reDecimalPoint.matcher(value);
242 value = value.replace(",", "");
243 value = value.replace(" ", "");
246 L("curr=" + currency + ", value=" + value);
247 final float val = Float.parseFloat(value);
248 lastAccount.addAmount(val, currency);
249 for (LedgerAccount syn : syntheticAccounts) {
250 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
251 currency, val, syn.getName()));
252 syn.addAmount(val, currency);
257 syntheticAccounts.clear();
258 state = ParserState.EXPECTING_ACCOUNT;
259 L("→ expecting account");
264 case EXPECTING_TRANSACTION:
265 if (!line.isEmpty() && (line.charAt(0) == ' '))
267 m = reTransactionStart.matcher(line);
269 transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
270 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
271 L(String.format(Locale.ENGLISH,
272 "found transaction %d → expecting description", transactionId));
273 progress.setProgress(++processedTransactionCount);
274 if (maxTransactionId < transactionId)
275 maxTransactionId = transactionId;
276 if ((progress.isIndeterminate()) ||
277 (progress.getTotal() < transactionId))
278 progress.setTotal(transactionId);
279 publishProgress(progress);
281 m = reEnd.matcher(line);
283 L("--- transaction value complete ---");
288 case EXPECTING_TRANSACTION_DESCRIPTION:
289 if (!line.isEmpty() && (line.charAt(0) == ' '))
291 m = reTransactionDescription.matcher(line);
293 if (transactionId == 0)
294 throw new TransactionParserException(
295 "Transaction Id is 0 while expecting description");
297 String date = Objects.requireNonNull(m.group(1));
299 int equalsIndex = date.indexOf('=');
300 if (equalsIndex >= 0)
301 date = date.substring(equalsIndex + 1);
303 new LedgerTransaction(transactionId, date, m.group(2));
305 catch (ParseException e) {
306 throw new TransactionParserException(
307 String.format("Error parsing date '%s'", date));
309 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
310 L(String.format(Locale.ENGLISH,
311 "transaction %d created for %s (%s) →" + " expecting details",
312 transactionId, date, m.group(2)));
316 case EXPECTING_TRANSACTION_DETAILS:
317 if (line.isEmpty()) {
318 // transaction data collected
320 transaction.finishLoading();
321 transactions.add(transaction);
323 state = ParserState.EXPECTING_TRANSACTION;
324 L(String.format("transaction %s parsed → expecting transaction",
325 transaction.getId()));
327 // sounds like a good idea, but transaction-1 may not be the first one chronologically
328 // for example, when you add the initial seeding transaction after entering some others
329 // if (transactionId == 1) {
330 // L("This was the initial transaction.
337 LedgerTransactionAccount lta = parseTransactionAccountLine(line);
339 transaction.addAccount(lta);
340 L(String.format(Locale.ENGLISH, "%d: %s = %s", transaction.getId(),
341 lta.getAccountName(), lta.getAmount()));
344 throw new IllegalStateException(
345 String.format("Can't parse transaction %d details: %s",
346 transactionId, line));
350 throw new RuntimeException(
351 String.format("Unknown parser updating %s", state.name()));
359 LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
360 ArrayList<LedgerAccount> createdAccounts) {
361 LedgerAccount acc = map.get(accountName);
366 String parentName = LedgerAccount.extractParentName(accountName);
367 LedgerAccount parentAccount;
368 if (parentName != null) {
369 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
372 parentAccount = null;
375 acc = new LedgerAccount(profile, accountName, parentAccount);
376 createdAccounts.add(acc);
379 private List<LedgerAccount> retrieveAccountList() throws IOException, HTTPException {
380 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
381 http.setAllowUserInteraction(false);
382 switch (http.getResponseCode()) {
388 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
390 publishProgress(Progress.indeterminate());
391 SQLiteDatabase db = App.getDatabase();
392 ArrayList<LedgerAccount> list = new ArrayList<>();
393 HashMap<String, LedgerAccount> map = new HashMap<>();
394 HashMap<String, LedgerAccount> currentMap = new HashMap<>();
395 for (LedgerAccount acc : prevAccounts)
396 currentMap.put(acc.getName(), acc);
398 try (InputStream resp = http.getInputStream()) {
400 if (http.getResponseCode() != 200)
401 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
403 AccountListParser parser = new AccountListParser(resp);
404 expectedPostingsCount = 0;
408 ParsedLedgerAccount parsedAccount = parser.nextAccount();
409 if (parsedAccount == null) {
412 expectedPostingsCount += parsedAccount.getAnumpostings();
413 final String accName = parsedAccount.getAname();
414 LedgerAccount acc = map.get(accName);
416 throw new RuntimeException(
417 String.format("Account '%s' already present", acc.getName()));
418 String parentName = LedgerAccount.extractParentName(accName);
419 ArrayList<LedgerAccount> createdParents = new ArrayList<>();
420 LedgerAccount parent;
421 if (parentName == null) {
425 parent = ensureAccountExists(parentName, map, createdParents);
426 parent.setHasSubAccounts(true);
428 acc = new LedgerAccount(profile, accName, parent);
430 map.put(accName, acc);
432 String lastCurrency = null;
433 float lastCurrencyAmount = 0;
434 for (ParsedBalance b : parsedAccount.getAibalance()) {
436 final String currency = b.getAcommodity();
437 final float amount = b.getAquantity()
439 if (currency.equals(lastCurrency)) {
440 lastCurrencyAmount += amount;
443 if (lastCurrency != null) {
444 acc.addAmount(lastCurrencyAmount, lastCurrency);
446 lastCurrency = currency;
447 lastCurrencyAmount = amount;
450 if (lastCurrency != null) {
451 acc.addAmount(lastCurrencyAmount, lastCurrency);
453 for (LedgerAccount p : createdParents)
454 acc.propagateAmountsTo(p);
459 // the current account tree may have changed, update the new-to be tree to match
460 for (LedgerAccount acc : list) {
461 LedgerAccount prevData = currentMap.get(acc.getName());
462 if (prevData != null) {
463 acc.setExpanded(prevData.isExpanded());
464 acc.setAmountsExpanded(prevData.amountsExpanded());
470 private List<LedgerTransaction> retrieveTransactionList()
471 throws IOException, ParseException, HTTPException {
472 Progress progress = new Progress();
473 progress.setTotal(expectedPostingsCount);
475 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
476 http.setAllowUserInteraction(false);
477 publishProgress(progress);
478 switch (http.getResponseCode()) {
484 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
486 ArrayList<LedgerTransaction> trList = new ArrayList<>();
487 try (InputStream resp = http.getInputStream()) {
490 TransactionListParser parser = new TransactionListParser(resp);
492 int processedPostings = 0;
496 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
498 if (parsedTransaction == null)
501 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
502 trList.add(transaction);
504 progress.setProgress(processedPostings += transaction.getAccounts()
506 // Logger.debug("trParser",
507 // String.format(Locale.US, "Parsed transaction %d - %s", transaction
509 // transaction.getDescription()));
510 // for (LedgerTransactionAccount acc : transaction.getAccounts()) {
511 // Logger.debug("trParser",
512 // String.format(Locale.US, " %s", acc.getAccountName()));
514 publishProgress(progress);
520 // json interface returns transactions if file order and the rest of the machinery
521 // expects them in reverse chronological order
522 Collections.sort(trList, (o1, o2) -> {
523 int res = o2.getDate()
524 .compareTo(o1.getDate());
527 return Integer.compare(o2.getId(), o1.getId());
532 @SuppressLint("DefaultLocale")
534 protected Result doInBackground(Void... params) {
535 Data.backgroundTaskStarted();
536 List<LedgerAccount> accounts;
537 List<LedgerTransaction> transactions;
539 accounts = retrieveAccountList();
540 if (accounts == null)
543 transactions = retrieveTransactionList();
544 if (accounts == null || transactions == null) {
545 accounts = new ArrayList<>();
546 transactions = new ArrayList<>();
547 retrieveTransactionListLegacy(accounts, transactions);
549 mainModel.setAndStoreAccountAndTransactionListFromWeb(accounts, transactions);
551 return new Result(accounts, transactions);
553 catch (MalformedURLException e) {
555 return new Result("Invalid server URL");
557 catch (HTTPException e) {
559 return new Result(String.format("HTTP error %d: %s", e.getResponseCode(),
560 e.getResponseMessage()));
562 catch (IOException e) {
564 return new Result(e.getLocalizedMessage());
566 catch (ParseException e) {
568 return new Result("Network error");
570 catch (OperationCanceledException e) {
572 return new Result("Operation cancelled");
575 Data.backgroundTaskFinished();
578 private void throwIfCancelled() {
580 throw new OperationCanceledException(null);
582 private enum ParserState {
583 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
584 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
587 public enum ProgressState {STARTING, RUNNING, FINISHED}
589 public static class Progress {
590 private int progress;
592 private ProgressState state = ProgressState.RUNNING;
593 private String error = null;
594 private boolean indeterminate;
596 indeterminate = true;
598 Progress(int progress, int total) {
599 this.indeterminate = false;
600 this.progress = progress;
603 public static Progress indeterminate() {
604 return new Progress();
606 public static Progress finished(String error) {
607 Progress p = new Progress();
608 p.setState(ProgressState.FINISHED);
612 public int getProgress() {
613 ensureState(ProgressState.RUNNING);
616 protected void setProgress(int progress) {
617 this.progress = progress;
618 this.state = ProgressState.RUNNING;
620 public int getTotal() {
621 ensureState(ProgressState.RUNNING);
624 protected void setTotal(int total) {
626 state = ProgressState.RUNNING;
627 indeterminate = total == -1;
629 private void ensureState(ProgressState wanted) {
631 throw new IllegalStateException(
632 String.format("Bad state: %s, expected %s", state, wanted));
634 public ProgressState getState() {
637 public void setState(ProgressState state) {
640 public String getError() {
641 ensureState(ProgressState.FINISHED);
644 public void setError(String error) {
646 state = ProgressState.FINISHED;
648 public boolean isIndeterminate() {
649 return indeterminate;
651 public void setIndeterminate(boolean indeterminate) {
652 this.indeterminate = indeterminate;
656 private static class TransactionParserException extends IllegalStateException {
657 TransactionParserException(String message) {
662 public static class Result {
664 public List<LedgerAccount> accounts;
665 public List<LedgerTransaction> transactions;
666 Result(String error) {
669 Result(List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
670 this.accounts = accounts;
671 this.transactions = transactions;