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 MainActivity context = getContext();
122 context.onRetrieveProgress(values[0]);
125 protected void onPreExecute() {
126 super.onPreExecute();
127 MainActivity context = getContext();
130 context.onRetrieveStart();
133 protected void onPostExecute(String error) {
134 super.onPostExecute(error);
135 MainActivity context = getContext();
138 context.onRetrieveDone(error);
141 protected void onCancelled() {
143 MainActivity context = getContext();
146 context.onRetrieveDone(null);
148 private String retrieveTransactionListLegacy() throws IOException, HTTPException {
149 Progress progress = new Progress();
150 int maxTransactionId = Progress.INDETERMINATE;
151 ArrayList<LedgerAccount> list = new ArrayList<>();
152 HashMap<String, LedgerAccount> map = new HashMap<>();
153 ArrayList<LedgerAccount> displayed = new ArrayList<>();
154 ArrayList<LedgerTransaction> transactions = new ArrayList<>();
155 LedgerAccount lastAccount = null;
156 ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
158 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
159 http.setAllowUserInteraction(false);
160 publishProgress(progress);
161 if (http.getResponseCode() != 200)
162 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
164 try (InputStream resp = http.getInputStream()) {
165 if (http.getResponseCode() != 200)
166 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
168 int matchedTransactionsCount = 0;
170 ParserState state = ParserState.EXPECTING_ACCOUNT;
173 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
175 int processedTransactionCount = 0;
176 int transactionId = 0;
177 LedgerTransaction transaction = null;
179 while ((line = buf.readLine()) != null) {
182 m = reComment.matcher(line);
184 // TODO: comments are ignored for now
185 // Log.v("transaction-parser", "Ignoring comment");
188 //L(String.format("State is %d", updating));
190 case EXPECTING_ACCOUNT:
191 if (line.equals("<h2>General Journal</h2>")) {
192 state = ParserState.EXPECTING_TRANSACTION;
193 L("→ expecting transaction");
196 m = reAccountName.matcher(line);
198 String acct_encoded = m.group(1);
199 String accName = URLDecoder.decode(acct_encoded, "UTF-8");
200 accName = accName.replace("\"", "");
201 L(String.format("found account: %s", accName));
203 lastAccount = map.get(accName);
204 if (lastAccount != null) {
205 L(String.format("ignoring duplicate account '%s'", accName));
208 String parentAccountName = LedgerAccount.extractParentName(accName);
209 LedgerAccount parentAccount;
210 if (parentAccountName != null) {
211 parentAccount = ensureAccountExists(parentAccountName, map,
215 parentAccount = null;
217 lastAccount = new LedgerAccount(profile, accName, parentAccount);
219 list.add(lastAccount);
220 map.put(accName, lastAccount);
222 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
223 L("→ expecting account amount");
227 case EXPECTING_ACCOUNT_AMOUNT:
228 m = reAccountValue.matcher(line);
229 boolean match_found = false;
234 String value = Objects.requireNonNull(m.group(1));
235 String currency = m.group(2);
236 if (currency == null)
240 Matcher tmpM = reDecimalComma.matcher(value);
242 value = value.replace(".", "");
243 value = value.replace(',', '.');
246 tmpM = reDecimalPoint.matcher(value);
248 value = value.replace(",", "");
249 value = value.replace(" ", "");
252 L("curr=" + currency + ", value=" + value);
253 final float val = Float.parseFloat(value);
254 lastAccount.addAmount(val, currency);
255 for (LedgerAccount syn : syntheticAccounts) {
256 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
257 currency, val, syn.getName()));
258 syn.addAmount(val, currency);
263 syntheticAccounts.clear();
264 state = ParserState.EXPECTING_ACCOUNT;
265 L("→ expecting account");
270 case EXPECTING_TRANSACTION:
271 if (!line.isEmpty() && (line.charAt(0) == ' '))
273 m = reTransactionStart.matcher(line);
275 transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
276 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
277 L(String.format(Locale.ENGLISH,
278 "found transaction %d → expecting description", transactionId));
279 progress.setProgress(++processedTransactionCount);
280 if (maxTransactionId < transactionId)
281 maxTransactionId = transactionId;
282 if ((progress.getTotal() == Progress.INDETERMINATE) ||
283 (progress.getTotal() < transactionId))
284 progress.setTotal(transactionId);
285 publishProgress(progress);
287 m = reEnd.matcher(line);
289 L("--- transaction value complete ---");
294 case EXPECTING_TRANSACTION_DESCRIPTION:
295 if (!line.isEmpty() && (line.charAt(0) == ' '))
297 m = reTransactionDescription.matcher(line);
299 if (transactionId == 0)
300 throw new TransactionParserException(
301 "Transaction Id is 0 while expecting " + "description");
303 String date = Objects.requireNonNull(m.group(1));
305 int equalsIndex = date.indexOf('=');
306 if (equalsIndex >= 0)
307 date = date.substring(equalsIndex + 1);
309 new LedgerTransaction(transactionId, date, m.group(2));
311 catch (ParseException e) {
313 return String.format("Error parsing date '%s'", date);
315 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
316 L(String.format(Locale.ENGLISH,
317 "transaction %d created for %s (%s) →" + " expecting details",
318 transactionId, date, m.group(2)));
322 case EXPECTING_TRANSACTION_DETAILS:
323 if (line.isEmpty()) {
324 // transaction data collected
326 transaction.finishLoading();
327 transactions.add(transaction);
329 state = ParserState.EXPECTING_TRANSACTION;
330 L(String.format("transaction %s parsed → expecting transaction",
331 transaction.getId()));
333 // sounds like a good idea, but transaction-1 may not be the first one chronologically
334 // for example, when you add the initial seeding transaction after entering some others
335 // if (transactionId == 1) {
336 // L("This was the initial transaction.
343 LedgerTransactionAccount lta = parseTransactionAccountLine(line);
345 transaction.addAccount(lta);
346 L(String.format(Locale.ENGLISH, "%d: %s = %s", transaction.getId(),
347 lta.getAccountName(), lta.getAmount()));
350 throw new IllegalStateException(
351 String.format("Can't parse transaction %d details: %s",
352 transactionId, line));
356 throw new RuntimeException(
357 String.format("Unknown parser updating %s", state.name()));
363 profile.setAndStoreAccountAndTransactionListFromWeb(list, transactions);
369 LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
370 ArrayList<LedgerAccount> createdAccounts) {
371 LedgerAccount acc = map.get(accountName);
376 String parentName = LedgerAccount.extractParentName(accountName);
377 LedgerAccount parentAccount;
378 if (parentName != null) {
379 parentAccount = ensureAccountExists(parentName, map, createdAccounts);
382 parentAccount = null;
385 acc = new LedgerAccount(profile, accountName, parentAccount);
386 createdAccounts.add(acc);
389 private boolean retrieveAccountList() throws IOException, HTTPException {
390 Progress progress = new Progress();
392 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
393 http.setAllowUserInteraction(false);
394 switch (http.getResponseCode()) {
400 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
402 publishProgress(progress);
403 SQLiteDatabase db = App.getDatabase();
404 ArrayList<LedgerAccount> list = new ArrayList<>();
405 HashMap<String, LedgerAccount> map = new HashMap<>();
406 HashMap<String, LedgerAccount> currentMap = new HashMap<>();
407 for (LedgerAccount acc : Objects.requireNonNull(profile.getAllAccounts()))
408 currentMap.put(acc.getName(), acc);
409 try (InputStream resp = http.getInputStream()) {
410 if (http.getResponseCode() != 200)
411 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
413 AccountListParser parser = new AccountListParser(resp);
417 ParsedLedgerAccount parsedAccount = parser.nextAccount();
418 if (parsedAccount == null) {
422 final String accName = parsedAccount.getAname();
423 LedgerAccount acc = map.get(accName);
425 throw new RuntimeException(
426 String.format("Account '%s' already present", acc.getName()));
427 String parentName = LedgerAccount.extractParentName(accName);
428 ArrayList<LedgerAccount> createdParents = new ArrayList<>();
429 LedgerAccount parent;
430 if (parentName == null) {
434 parent = ensureAccountExists(parentName, map, createdParents);
435 parent.setHasSubAccounts(true);
437 acc = new LedgerAccount(profile, accName, parent);
439 map.put(accName, acc);
441 String lastCurrency = null;
442 float lastCurrencyAmount = 0;
443 for (ParsedBalance b : parsedAccount.getAibalance()) {
445 final String currency = b.getAcommodity();
446 final float amount = b.getAquantity()
448 if (currency.equals(lastCurrency)) {
449 lastCurrencyAmount += amount;
452 if (lastCurrency != null) {
453 acc.addAmount(lastCurrencyAmount, lastCurrency);
455 lastCurrency = currency;
456 lastCurrencyAmount = amount;
459 if (lastCurrency != null) {
460 acc.addAmount(lastCurrencyAmount, lastCurrency);
462 for (LedgerAccount p : createdParents)
463 acc.propagateAmountsTo(p);
468 // the current account tree may have changed, update the new-to be tree to match
469 for (LedgerAccount acc : list) {
470 LedgerAccount prevData = currentMap.get(acc.getName());
471 if (prevData != null) {
472 acc.setExpanded(prevData.isExpanded());
473 acc.setAmountsExpanded(prevData.amountsExpanded());
477 profile.setAndStoreAccountListFromWeb(list);
480 private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
481 Progress progress = new Progress();
482 int maxTransactionId = Data.transactions.size();
484 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
485 http.setAllowUserInteraction(false);
486 publishProgress(progress);
487 switch (http.getResponseCode()) {
493 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
495 try (InputStream resp = http.getInputStream()) {
497 ArrayList<LedgerTransaction> trList = new ArrayList<>();
499 TransactionListParser parser = new TransactionListParser(resp);
501 int processedTransactionCount = 0;
505 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
507 if (parsedTransaction == null)
510 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
511 trList.add(transaction);
513 progress.setProgress(++processedTransactionCount);
514 publishProgress(progress);
518 profile.setAndStoreTransactionList(trList);
524 @SuppressLint("DefaultLocale")
526 protected String doInBackground(Void... params) {
527 Data.backgroundTaskStarted();
529 if (!retrieveAccountList() || !retrieveTransactionList())
530 return retrieveTransactionListLegacy();
533 catch (MalformedURLException e) {
535 return "Invalid server URL";
537 catch (HTTPException e) {
539 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
541 catch (IOException e) {
543 return e.getLocalizedMessage();
545 catch (ParseException e) {
547 return "Network error";
549 catch (OperationCanceledException e) {
551 return "Operation cancelled";
554 Data.backgroundTaskFinished();
557 private MainActivity getContext() {
558 return contextRef.get();
560 private void throwIfCancelled() {
562 throw new OperationCanceledException(null);
564 private enum ParserState {
565 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
566 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
569 public static class Progress {
570 public static final int INDETERMINATE = -1;
571 private int progress;
574 this(INDETERMINATE, INDETERMINATE);
576 Progress(int progress, int total) {
577 this.progress = progress;
580 public int getProgress() {
583 protected void setProgress(int progress) {
584 this.progress = progress;
586 public int getTotal() {
589 protected void setTotal(int total) {
594 private static class TransactionParserException extends IllegalStateException {
595 TransactionParserException(String message) {