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 final Pattern reAccountName =
78 Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
79 private final Pattern reAccountValue = Pattern.compile(
80 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
81 private final MainModel mainModel;
82 private final MobileLedgerProfile profile;
83 private final List<LedgerAccount> prevAccounts;
84 private int expectedPostingsCount = -1;
85 public RetrieveTransactionsTask(@NonNull MainModel mainModel,
86 @NonNull MobileLedgerProfile profile,
87 List<LedgerAccount> accounts) {
88 this.mainModel = mainModel;
89 this.profile = profile;
90 this.prevAccounts = accounts;
92 private static void L(String msg) {
93 //debug("transaction-parser", msg);
95 static LedgerTransactionAccount parseTransactionAccountLine(String line) {
96 Matcher m = reTransactionDetails.matcher(line);
98 String postingStatus = m.group(1);
99 String acc_name = m.group(2);
100 String currencyPre = m.group(3);
101 String amount = Objects.requireNonNull(m.group(4));
102 String currencyPost = m.group(5);
104 String currency = null;
105 if ((currencyPre != null) && (currencyPre.length() > 0)) {
106 if ((currencyPost != null) && (currencyPost.length() > 0))
108 currency = currencyPre;
110 else if ((currencyPost != null) && (currencyPost.length() > 0)) {
111 currency = currencyPost;
114 amount = amount.replace(',', '.');
116 return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
123 protected void onProgressUpdate(Progress... values) {
124 super.onProgressUpdate(values);
125 Data.backgroundTaskProgress.postValue(values[0]);
128 protected void onPostExecute(Result result) {
129 super.onPostExecute(result);
130 Progress progress = new Progress();
131 progress.setState(ProgressState.FINISHED);
132 progress.setError(result.error);
133 onProgressUpdate(progress);
136 protected void onCancelled() {
138 Progress progress = new Progress();
139 progress.setState(ProgressState.FINISHED);
140 onProgressUpdate(progress);
142 private void retrieveTransactionListLegacy(List<LedgerAccount> accounts,
143 List<LedgerTransaction> transactions)
144 throws IOException, HTTPException {
145 Progress progress = Progress.indeterminate();
146 progress.setState(ProgressState.RUNNING);
147 progress.setTotal(expectedPostingsCount);
148 int maxTransactionId = -1;
149 HashMap<String, LedgerAccount> map = new HashMap<>();
150 LedgerAccount lastAccount = null;
151 ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
153 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
154 http.setAllowUserInteraction(false);
155 publishProgress(progress);
156 if (http.getResponseCode() != 200)
157 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
159 try (InputStream resp = http.getInputStream()) {
160 if (http.getResponseCode() != 200)
161 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
163 int matchedTransactionsCount = 0;
165 ParserState state = ParserState.EXPECTING_ACCOUNT;
168 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
170 int processedTransactionCount = 0;
171 int transactionId = 0;
172 LedgerTransaction transaction = null;
174 while ((line = buf.readLine()) != null) {
177 m = reComment.matcher(line);
179 // TODO: comments are ignored for now
180 // Log.v("transaction-parser", "Ignoring comment");
183 //L(String.format("State is %d", updating));
185 case EXPECTING_ACCOUNT:
186 if (line.equals("<h2>General Journal</h2>")) {
187 state = ParserState.EXPECTING_TRANSACTION;
188 L("→ expecting transaction");
191 m = reAccountName.matcher(line);
193 String acct_encoded = m.group(1);
194 String accName = URLDecoder.decode(acct_encoded, "UTF-8");
195 accName = accName.replace("\"", "");
196 L(String.format("found account: %s", accName));
198 lastAccount = map.get(accName);
199 if (lastAccount != null) {
200 L(String.format("ignoring duplicate account '%s'", accName));
203 String parentAccountName = LedgerAccount.extractParentName(accName);
204 LedgerAccount parentAccount;
205 if (parentAccountName != null) {
206 parentAccount = ensureAccountExists(parentAccountName, map,
210 parentAccount = null;
212 lastAccount = new LedgerAccount(profile, accName, parentAccount);
214 accounts.add(lastAccount);
215 map.put(accName, lastAccount);
217 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
218 L("→ expecting account amount");
222 case EXPECTING_ACCOUNT_AMOUNT:
223 m = reAccountValue.matcher(line);
224 boolean match_found = false;
229 String value = Objects.requireNonNull(m.group(1));
230 String currency = m.group(2);
231 if (currency == null)
235 Matcher tmpM = reDecimalComma.matcher(value);
237 value = value.replace(".", "");
238 value = value.replace(',', '.');
241 tmpM = reDecimalPoint.matcher(value);
243 value = value.replace(",", "");
244 value = value.replace(" ", "");
247 L("curr=" + currency + ", value=" + value);
248 final float val = Float.parseFloat(value);
249 lastAccount.addAmount(val, currency);
250 for (LedgerAccount syn : syntheticAccounts) {
251 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
252 currency, val, syn.getName()));
253 syn.addAmount(val, currency);
258 syntheticAccounts.clear();
259 state = ParserState.EXPECTING_ACCOUNT;
260 L("→ expecting account");
265 case EXPECTING_TRANSACTION:
266 if (!line.isEmpty() && (line.charAt(0) == ' '))
268 m = reTransactionStart.matcher(line);
270 transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
271 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
272 L(String.format(Locale.ENGLISH,
273 "found transaction %d → expecting description", transactionId));
274 progress.setProgress(++processedTransactionCount);
275 if (maxTransactionId < transactionId)
276 maxTransactionId = transactionId;
277 if ((progress.isIndeterminate()) ||
278 (progress.getTotal() < transactionId))
279 progress.setTotal(transactionId);
280 publishProgress(progress);
282 m = reEnd.matcher(line);
284 L("--- transaction value complete ---");
289 case EXPECTING_TRANSACTION_DESCRIPTION:
290 if (!line.isEmpty() && (line.charAt(0) == ' '))
292 m = reTransactionDescription.matcher(line);
294 if (transactionId == 0)
295 throw new TransactionParserException(
296 "Transaction Id is 0 while expecting description");
298 String date = Objects.requireNonNull(m.group(1));
300 int equalsIndex = date.indexOf('=');
301 if (equalsIndex >= 0)
302 date = date.substring(equalsIndex + 1);
304 new LedgerTransaction(transactionId, date, m.group(2));
306 catch (ParseException e) {
307 throw new TransactionParserException(
308 String.format("Error parsing date '%s'", date));
310 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
311 L(String.format(Locale.ENGLISH,
312 "transaction %d created for %s (%s) →" + " expecting details",
313 transactionId, date, m.group(2)));
317 case EXPECTING_TRANSACTION_DETAILS:
318 if (line.isEmpty()) {
319 // transaction data collected
321 transaction.finishLoading();
322 transactions.add(transaction);
324 state = ParserState.EXPECTING_TRANSACTION;
325 L(String.format("transaction %s parsed → expecting transaction",
326 transaction.getId()));
328 // sounds like a good idea, but transaction-1 may not be the first one chronologically
329 // for example, when you add the initial seeding transaction after entering some others
330 // if (transactionId == 1) {
331 // L("This was the initial transaction.
338 LedgerTransactionAccount lta = parseTransactionAccountLine(line);
340 transaction.addAccount(lta);
341 L(String.format(Locale.ENGLISH, "%d: %s = %s", transaction.getId(),
342 lta.getAccountName(), lta.getAmount()));
345 throw new IllegalStateException(
346 String.format("Can't parse transaction %d details: %s",
347 transactionId, line));
351 throw new RuntimeException(
352 String.format("Unknown parser updating %s", state.name()));
360 LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
361 ArrayList<LedgerAccount> createdAccounts) {
362 LedgerAccount acc = map.get(accountName);
367 String parentName = LedgerAccount.extractParentName(accountName);
368 LedgerAccount parentAccount;
369 if (parentName != null) {
370 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
373 parentAccount = null;
376 acc = new LedgerAccount(profile, accountName, parentAccount);
377 createdAccounts.add(acc);
380 private List<LedgerAccount> retrieveAccountList() throws IOException, HTTPException {
381 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
382 http.setAllowUserInteraction(false);
383 switch (http.getResponseCode()) {
389 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
391 publishProgress(Progress.indeterminate());
392 SQLiteDatabase db = App.getDatabase();
393 ArrayList<LedgerAccount> list = new ArrayList<>();
394 HashMap<String, LedgerAccount> map = new HashMap<>();
395 HashMap<String, LedgerAccount> currentMap = new HashMap<>();
396 for (LedgerAccount acc : prevAccounts)
397 currentMap.put(acc.getName(), acc);
399 try (InputStream resp = http.getInputStream()) {
401 if (http.getResponseCode() != 200)
402 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
404 AccountListParser parser = new AccountListParser(resp);
405 expectedPostingsCount = 0;
409 ParsedLedgerAccount parsedAccount = parser.nextAccount();
410 if (parsedAccount == null) {
413 expectedPostingsCount += parsedAccount.getAnumpostings();
414 final String accName = parsedAccount.getAname();
415 LedgerAccount acc = map.get(accName);
417 throw new RuntimeException(
418 String.format("Account '%s' already present", acc.getName()));
419 String parentName = LedgerAccount.extractParentName(accName);
420 ArrayList<LedgerAccount> createdParents = new ArrayList<>();
421 LedgerAccount parent;
422 if (parentName == null) {
426 parent = ensureAccountExists(parentName, map, createdParents);
427 parent.setHasSubAccounts(true);
429 acc = new LedgerAccount(profile, accName, parent);
431 map.put(accName, acc);
433 String lastCurrency = null;
434 float lastCurrencyAmount = 0;
435 for (ParsedBalance b : parsedAccount.getAibalance()) {
437 final String currency = b.getAcommodity();
438 final float amount = b.getAquantity()
440 if (currency.equals(lastCurrency)) {
441 lastCurrencyAmount += amount;
444 if (lastCurrency != null) {
445 acc.addAmount(lastCurrencyAmount, lastCurrency);
447 lastCurrency = currency;
448 lastCurrencyAmount = amount;
451 if (lastCurrency != null) {
452 acc.addAmount(lastCurrencyAmount, lastCurrency);
454 for (LedgerAccount p : createdParents)
455 acc.propagateAmountsTo(p);
460 // the current account tree may have changed, update the new-to be tree to match
461 for (LedgerAccount acc : list) {
462 LedgerAccount prevData = currentMap.get(acc.getName());
463 if (prevData != null) {
464 acc.setExpanded(prevData.isExpanded());
465 acc.setAmountsExpanded(prevData.amountsExpanded());
471 private List<LedgerTransaction> retrieveTransactionList()
472 throws IOException, ParseException, HTTPException {
473 Progress progress = new Progress();
474 progress.setTotal(expectedPostingsCount);
476 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
477 http.setAllowUserInteraction(false);
478 publishProgress(progress);
479 switch (http.getResponseCode()) {
485 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
487 ArrayList<LedgerTransaction> trList = new ArrayList<>();
488 try (InputStream resp = http.getInputStream()) {
491 TransactionListParser parser = new TransactionListParser(resp);
493 int processedPostings = 0;
497 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
499 if (parsedTransaction == null)
502 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
503 trList.add(transaction);
505 progress.setProgress(processedPostings += transaction.getAccounts()
507 // Logger.debug("trParser",
508 // String.format(Locale.US, "Parsed transaction %d - %s", transaction
510 // transaction.getDescription()));
511 // for (LedgerTransactionAccount acc : transaction.getAccounts()) {
512 // Logger.debug("trParser",
513 // String.format(Locale.US, " %s", acc.getAccountName()));
515 publishProgress(progress);
521 // json interface returns transactions if file order and the rest of the machinery
522 // expects them in reverse chronological order
523 Collections.sort(trList, (o1, o2) -> {
524 int res = o2.getDate()
525 .compareTo(o1.getDate());
528 return Integer.compare(o2.getId(), o1.getId());
533 @SuppressLint("DefaultLocale")
535 protected Result doInBackground(Void... params) {
536 Data.backgroundTaskStarted();
537 List<LedgerAccount> accounts;
538 List<LedgerTransaction> transactions;
540 accounts = retrieveAccountList();
541 if (accounts == null)
544 transactions = retrieveTransactionList();
545 if (accounts == null || transactions == null) {
546 accounts = new ArrayList<>();
547 transactions = new ArrayList<>();
548 retrieveTransactionListLegacy(accounts, transactions);
550 mainModel.setAndStoreAccountAndTransactionListFromWeb(accounts, transactions);
552 return new Result(accounts, transactions);
554 catch (MalformedURLException e) {
556 return new Result("Invalid server URL");
558 catch (HTTPException e) {
560 return new Result(String.format("HTTP error %d: %s", e.getResponseCode(),
561 e.getResponseMessage()));
563 catch (IOException e) {
565 return new Result(e.getLocalizedMessage());
567 catch (ParseException e) {
569 return new Result("Network error");
571 catch (OperationCanceledException e) {
573 return new Result("Operation cancelled");
576 Data.backgroundTaskFinished();
579 private void throwIfCancelled() {
581 throw new OperationCanceledException(null);
583 private enum ParserState {
584 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
585 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
588 public enum ProgressState {STARTING, RUNNING, FINISHED}
590 public static class Progress {
591 private int progress;
593 private ProgressState state = ProgressState.RUNNING;
594 private String error = null;
595 private boolean indeterminate;
597 indeterminate = true;
599 Progress(int progress, int total) {
600 this.indeterminate = false;
601 this.progress = progress;
604 public static Progress indeterminate() {
605 return new Progress();
607 public static Progress finished(String error) {
608 Progress p = new Progress();
609 p.setState(ProgressState.FINISHED);
613 public int getProgress() {
614 ensureState(ProgressState.RUNNING);
617 protected void setProgress(int progress) {
618 this.progress = progress;
619 this.state = ProgressState.RUNNING;
621 public int getTotal() {
622 ensureState(ProgressState.RUNNING);
625 protected void setTotal(int total) {
627 state = ProgressState.RUNNING;
628 indeterminate = total == -1;
630 private void ensureState(ProgressState wanted) {
632 throw new IllegalStateException(
633 String.format("Bad state: %s, expected %s", state, wanted));
635 public ProgressState getState() {
638 public void setState(ProgressState state) {
641 public String getError() {
642 ensureState(ProgressState.FINISHED);
645 public void setError(String error) {
647 state = ProgressState.FINISHED;
649 public boolean isIndeterminate() {
650 return indeterminate;
652 public void setIndeterminate(boolean indeterminate) {
653 this.indeterminate = indeterminate;
657 private static class TransactionParserException extends IllegalStateException {
658 TransactionParserException(String message) {
663 public static class Result {
665 public List<LedgerAccount> accounts;
666 public List<LedgerTransaction> transactions;
667 Result(String error) {
670 Result(List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
671 this.accounts = accounts;
672 this.transactions = transactions;