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.activity.MainActivity;
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.lang.ref.WeakReference;
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.HashMap;
54 import java.util.Locale;
55 import java.util.Objects;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
60 public class RetrieveTransactionsTask
61 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
62 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
63 private static final Pattern reComment = Pattern.compile("^\\s*;");
64 private static final Pattern reTransactionStart = Pattern.compile(
65 "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
66 "\"[^\"]*>([\\d.-]+)</td>");
67 private static final Pattern reTransactionDescription =
68 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
69 private static final Pattern reTransactionDetails = Pattern.compile(
70 "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
71 "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
72 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
73 private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
74 private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
75 private WeakReference<MainActivity> contextRef;
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 MobileLedgerProfile profile;
81 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
82 @NonNull MobileLedgerProfile profile) {
83 this.contextRef = contextRef;
84 this.profile = profile;
86 private static void L(String msg) {
87 //debug("transaction-parser", msg);
89 static LedgerTransactionAccount parseTransactionAccountLine(String line) {
90 Matcher m = reTransactionDetails.matcher(line);
92 String postingStatus = m.group(1);
93 String acc_name = m.group(2);
94 String currencyPre = m.group(3);
95 String amount = Objects.requireNonNull(m.group(4));
96 String currencyPost = m.group(5);
98 String currency = null;
99 if ((currencyPre != null) && (currencyPre.length() > 0)) {
100 if ((currencyPost != null) && (currencyPost.length() > 0))
102 currency = currencyPre;
104 else if ((currencyPost != null) && (currencyPost.length() > 0)) {
105 currency = currencyPost;
108 amount = amount.replace(',', '.');
110 return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
117 protected void onProgressUpdate(Progress... values) {
118 super.onProgressUpdate(values);
119 Data.backgroundTaskProgress.postValue(values[0]);
122 protected void onPreExecute() {
123 super.onPreExecute();
124 MainActivity context = getContext();
127 context.onRetrieveStart();
130 protected void onPostExecute(String error) {
131 super.onPostExecute(error);
132 Progress progress = new Progress();
133 progress.setState(ProgressState.FINISHED);
134 progress.setError(error);
135 onProgressUpdate(progress);
138 protected void onCancelled() {
140 Progress progress = new Progress();
141 progress.setState(ProgressState.FINISHED);
142 onProgressUpdate(progress);
144 private String retrieveTransactionListLegacy() throws IOException, HTTPException {
145 Progress progress = Progress.indeterminate();
146 progress.setState(ProgressState.RUNNING);
147 int maxTransactionId = -1;
148 ArrayList<LedgerAccount> list = new ArrayList<>();
149 HashMap<String, LedgerAccount> map = new HashMap<>();
150 ArrayList<LedgerAccount> displayed = new ArrayList<>();
151 ArrayList<LedgerTransaction> transactions = new ArrayList<>();
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(profile, accName, parentAccount);
216 list.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) {
310 return 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()));
360 profile.setAndStoreAccountAndTransactionListFromWeb(list, transactions);
366 LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
367 ArrayList<LedgerAccount> createdAccounts) {
368 LedgerAccount acc = map.get(accountName);
373 String parentName = LedgerAccount.extractParentName(accountName);
374 LedgerAccount parentAccount;
375 if (parentName != null) {
376 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
379 parentAccount = null;
382 acc = new LedgerAccount(profile, accountName, parentAccount);
383 createdAccounts.add(acc);
386 private boolean retrieveAccountList() throws IOException, HTTPException {
387 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
388 http.setAllowUserInteraction(false);
389 switch (http.getResponseCode()) {
395 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
397 publishProgress(Progress.indeterminate());
398 SQLiteDatabase db = App.getDatabase();
399 ArrayList<LedgerAccount> list = new ArrayList<>();
400 HashMap<String, LedgerAccount> map = new HashMap<>();
401 HashMap<String, LedgerAccount> currentMap = new HashMap<>();
402 for (LedgerAccount acc : Objects.requireNonNull(profile.getAllAccounts()))
403 currentMap.put(acc.getName(), acc);
404 try (InputStream resp = http.getInputStream()) {
405 if (http.getResponseCode() != 200)
406 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
408 AccountListParser parser = new AccountListParser(resp);
412 ParsedLedgerAccount parsedAccount = parser.nextAccount();
413 if (parsedAccount == null) {
417 final String accName = parsedAccount.getAname();
418 LedgerAccount acc = map.get(accName);
420 throw new RuntimeException(
421 String.format("Account '%s' already present", acc.getName()));
422 String parentName = LedgerAccount.extractParentName(accName);
423 ArrayList<LedgerAccount> createdParents = new ArrayList<>();
424 LedgerAccount parent;
425 if (parentName == null) {
429 parent = ensureAccountExists(parentName, map, createdParents);
430 parent.setHasSubAccounts(true);
432 acc = new LedgerAccount(profile, accName, parent);
434 map.put(accName, acc);
436 String lastCurrency = null;
437 float lastCurrencyAmount = 0;
438 for (ParsedBalance b : parsedAccount.getAibalance()) {
440 final String currency = b.getAcommodity();
441 final float amount = b.getAquantity()
443 if (currency.equals(lastCurrency)) {
444 lastCurrencyAmount += amount;
447 if (lastCurrency != null) {
448 acc.addAmount(lastCurrencyAmount, lastCurrency);
450 lastCurrency = currency;
451 lastCurrencyAmount = amount;
454 if (lastCurrency != null) {
455 acc.addAmount(lastCurrencyAmount, lastCurrency);
457 for (LedgerAccount p : createdParents)
458 acc.propagateAmountsTo(p);
463 // the current account tree may have changed, update the new-to be tree to match
464 for (LedgerAccount acc : list) {
465 LedgerAccount prevData = currentMap.get(acc.getName());
466 if (prevData != null) {
467 acc.setExpanded(prevData.isExpanded());
468 acc.setAmountsExpanded(prevData.amountsExpanded());
472 profile.setAndStoreAccountListFromWeb(list);
475 private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
476 Progress progress = new Progress();
477 int maxTransactionId = Data.transactions.size();
479 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
480 http.setAllowUserInteraction(false);
481 publishProgress(progress);
482 switch (http.getResponseCode()) {
488 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
490 try (InputStream resp = http.getInputStream()) {
492 ArrayList<LedgerTransaction> trList = new ArrayList<>();
494 TransactionListParser parser = new TransactionListParser(resp);
496 int processedTransactionCount = 0;
500 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
502 if (parsedTransaction == null)
505 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
506 trList.add(transaction);
508 progress.setProgress(++processedTransactionCount);
509 publishProgress(progress);
513 profile.setAndStoreTransactionList(trList);
519 @SuppressLint("DefaultLocale")
521 protected String doInBackground(Void... params) {
522 Data.backgroundTaskStarted();
524 if (!retrieveAccountList() || !retrieveTransactionList())
525 return retrieveTransactionListLegacy();
528 catch (MalformedURLException e) {
530 return "Invalid server URL";
532 catch (HTTPException e) {
534 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
536 catch (IOException e) {
538 return e.getLocalizedMessage();
540 catch (ParseException e) {
542 return "Network error";
544 catch (OperationCanceledException e) {
546 return "Operation cancelled";
549 Data.backgroundTaskFinished();
552 private MainActivity getContext() {
553 return contextRef.get();
555 private void throwIfCancelled() {
557 throw new OperationCanceledException(null);
559 private enum ParserState {
560 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
561 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
564 public enum ProgressState {STARTING, RUNNING, FINISHED}
566 public static class Progress {
567 private int progress;
569 private ProgressState state = ProgressState.RUNNING;
570 private String error = null;
571 private boolean indeterminate;
573 indeterminate = true;
575 Progress(int progress, int total) {
576 this.indeterminate = false;
577 this.progress = progress;
580 public static Progress indeterminate() {
581 return new Progress();
583 public static Progress finished(String error) {
584 Progress p = new Progress();
585 p.setState(ProgressState.FINISHED);
589 public int getProgress() {
590 ensureState(ProgressState.RUNNING);
593 protected void setProgress(int progress) {
594 this.progress = progress;
595 this.state = ProgressState.RUNNING;
597 public int getTotal() {
598 ensureState(ProgressState.RUNNING);
601 protected void setTotal(int total) {
603 state = ProgressState.RUNNING;
605 private void ensureState(ProgressState wanted) {
607 throw new IllegalStateException(
608 String.format("Bad state: %s, expected %s", state, wanted));
610 public ProgressState getState() {
613 public void setState(ProgressState state) {
616 public String getError() {
617 ensureState(ProgressState.FINISHED);
620 public void setError(String error) {
622 state = ProgressState.FINISHED;
624 public boolean isIndeterminate() {
625 return indeterminate;
627 public void setIndeterminate(boolean indeterminate) {
628 this.indeterminate = indeterminate;
632 private static class TransactionParserException extends IllegalStateException {
633 TransactionParserException(String message) {