2 * Copyright © 2019 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 net.ktnx.mobileledger.App;
26 import net.ktnx.mobileledger.err.HTTPException;
27 import net.ktnx.mobileledger.json.AccountListParser;
28 import net.ktnx.mobileledger.json.ParsedBalance;
29 import net.ktnx.mobileledger.json.ParsedLedgerAccount;
30 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
31 import net.ktnx.mobileledger.json.TransactionListParser;
32 import net.ktnx.mobileledger.model.Data;
33 import net.ktnx.mobileledger.model.LedgerAccount;
34 import net.ktnx.mobileledger.model.LedgerTransaction;
35 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
36 import net.ktnx.mobileledger.model.MobileLedgerProfile;
37 import net.ktnx.mobileledger.ui.activity.MainActivity;
38 import net.ktnx.mobileledger.utils.NetworkUtil;
40 import java.io.BufferedReader;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.InputStreamReader;
44 import java.lang.ref.WeakReference;
45 import java.net.HttpURLConnection;
46 import java.net.MalformedURLException;
47 import java.net.URLDecoder;
48 import java.nio.charset.StandardCharsets;
49 import java.text.ParseException;
50 import java.util.ArrayList;
51 import java.util.HashMap;
52 import java.util.Locale;
53 import java.util.Stack;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
57 import androidx.annotation.NonNull;
59 import static net.ktnx.mobileledger.utils.Logger.debug;
62 public class RetrieveTransactionsTask
63 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
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("<tr class=\"title\" " +
67 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
68 private static final Pattern reTransactionDescription =
69 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
70 private static final Pattern reTransactionDetails =
71 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
72 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
73 private WeakReference<MainActivity> contextRef;
75 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
76 private Pattern reAccountValue = Pattern.compile(
77 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
78 private MobileLedgerProfile profile;
79 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
80 @NonNull MobileLedgerProfile profile) {
81 this.contextRef = contextRef;
82 this.profile = profile;
84 private static void L(String msg) {
85 //debug("transaction-parser", msg);
88 protected void onProgressUpdate(Progress... values) {
89 super.onProgressUpdate(values);
90 MainActivity context = getContext();
91 if (context == null) return;
92 context.onRetrieveProgress(values[0]);
95 protected void onPreExecute() {
97 MainActivity context = getContext();
98 if (context == null) return;
99 context.onRetrieveStart();
102 protected void onPostExecute(String error) {
103 super.onPostExecute(error);
104 MainActivity context = getContext();
105 if (context == null) return;
106 context.onRetrieveDone(error);
109 protected void onCancelled() {
111 MainActivity context = getContext();
112 if (context == null) return;
113 context.onRetrieveDone(null);
115 private String retrieveTransactionListLegacy()
116 throws IOException, ParseException, HTTPException {
117 Progress progress = new Progress();
118 int maxTransactionId = Progress.INDETERMINATE;
119 ArrayList<LedgerAccount> accountList = new ArrayList<>();
120 HashMap<String, Void> accountNames = new HashMap<>();
121 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
122 LedgerAccount lastAccount = null, prevAccount = null;
123 boolean onlyStarred = Data.optShowOnlyStarred.get();
125 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
126 http.setAllowUserInteraction(false);
127 publishProgress(progress);
128 switch (http.getResponseCode()) {
132 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
135 SQLiteDatabase db = App.getDatabase();
136 try (InputStream resp = http.getInputStream()) {
137 if (http.getResponseCode() != 200)
138 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
139 db.beginTransaction();
141 prepareDbForRetrieval(db, profile);
143 int matchedTransactionsCount = 0;
146 ParserState state = ParserState.EXPECTING_ACCOUNT;
149 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
151 int processedTransactionCount = 0;
152 int transactionId = 0;
153 LedgerTransaction transaction = null;
155 while ((line = buf.readLine()) != null) {
158 m = reComment.matcher(line);
160 // TODO: comments are ignored for now
161 // Log.v("transaction-parser", "Ignoring comment");
164 //L(String.format("State is %d", updating));
166 case EXPECTING_ACCOUNT:
167 if (line.equals("<h2>General Journal</h2>")) {
168 state = ParserState.EXPECTING_TRANSACTION;
169 L("→ expecting transaction");
170 // commit the current transaction and start a new one
171 // the account list in the UI should reflect the (committed)
172 // state of the database
173 db.setTransactionSuccessful();
175 Data.accounts.setList(accountList);
176 db.beginTransaction();
179 m = reAccountName.matcher(line);
181 String acct_encoded = m.group(1);
182 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
183 acct_name = acct_name.replace("\"", "");
184 L(String.format("found account: %s", acct_name));
186 prevAccount = lastAccount;
187 lastAccount = profile.tryLoadAccount(db, acct_name);
188 if (lastAccount == null) lastAccount = new LedgerAccount(acct_name);
189 else lastAccount.removeAmounts();
190 profile.storeAccount(db, lastAccount);
192 if (prevAccount != null) prevAccount
193 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
194 // make sure the parent account(s) are present,
195 // synthesising them if necessary
196 // this happens when the (missing-in-HTML) parent account has
197 // only one child so we create a synthetic parent account record,
198 // copying the amounts when child's amounts are parsed
199 String parentName = lastAccount.getParentName();
200 if (parentName != null) {
201 Stack<String> toAppend = new Stack<>();
202 while (parentName != null) {
203 if (accountNames.containsKey(parentName)) break;
204 toAppend.push(parentName);
205 parentName = new LedgerAccount(parentName).getParentName();
207 syntheticAccounts.clear();
208 while (!toAppend.isEmpty()) {
209 String aName = toAppend.pop();
210 LedgerAccount acc = profile.tryLoadAccount(db, aName);
212 acc = new LedgerAccount(aName);
213 acc.setHiddenByStar(lastAccount.isHiddenByStar());
214 acc.setExpanded(!lastAccount.hasSubAccounts() ||
215 lastAccount.isExpanded());
217 acc.setHasSubAccounts(true);
218 acc.removeAmounts(); // filled below when amounts are parsed
219 if ((!onlyStarred || !acc.isHiddenByStar()) &&
220 acc.isVisible(accountList)) accountList.add(acc);
221 L(String.format("gap-filling with %s", aName));
222 accountNames.put(aName, null);
223 profile.storeAccount(db, acc);
224 syntheticAccounts.put(aName, acc);
228 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
229 lastAccount.isVisible(accountList))
230 accountList.add(lastAccount);
231 accountNames.put(acct_name, null);
233 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
234 L("→ expecting account amount");
238 case EXPECTING_ACCOUNT_AMOUNT:
239 m = reAccountValue.matcher(line);
240 boolean match_found = false;
245 String value = m.group(1);
246 String currency = m.group(2);
247 if (currency == null) currency = "";
248 value = value.replace(',', '.');
249 L("curr=" + currency + ", value=" + value);
250 final float val = Float.parseFloat(value);
251 profile.storeAccountValue(db, lastAccount.getName(), currency, val);
252 lastAccount.addAmount(val, currency);
253 for (LedgerAccount syn : syntheticAccounts.values()) {
254 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
255 currency, val, syn.getName()));
256 syn.addAmount(val, currency);
257 profile.storeAccountValue(db, syn.getName(), currency, val);
262 syntheticAccounts.clear();
263 state = ParserState.EXPECTING_ACCOUNT;
264 L("→ expecting account");
269 case EXPECTING_TRANSACTION:
270 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
271 m = reTransactionStart.matcher(line);
273 transactionId = Integer.valueOf(m.group(1));
274 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
275 L(String.format(Locale.ENGLISH,
276 "found transaction %d → expecting description",
278 progress.setProgress(++processedTransactionCount);
279 if (maxTransactionId < transactionId)
280 maxTransactionId = transactionId;
281 if ((progress.getTotal() == Progress.INDETERMINATE) ||
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) == ' ')) continue;
295 m = reTransactionDescription.matcher(line);
297 if (transactionId == 0) throw new TransactionParserException(
298 "Transaction Id is 0 while expecting " + "description");
300 String date = m.group(1);
302 int equalsIndex = date.indexOf('=');
303 if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
305 new LedgerTransaction(transactionId, date, m.group(2));
307 catch (ParseException e) {
309 return String.format("Error parsing date '%s'", date);
311 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
312 L(String.format(Locale.ENGLISH,
313 "transaction %d created for %s (%s) →" +
314 " expecting details", transactionId, date, m.group(2)));
318 case EXPECTING_TRANSACTION_DETAILS:
319 if (line.isEmpty()) {
320 // transaction data collected
321 if (transaction.existsInDb(db)) {
322 profile.markTransactionAsPresent(db, transaction);
323 matchedTransactionsCount++;
325 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
326 profile.markTransactionsBeforeTransactionAsPresent(db,
328 progress.setTotal(progress.getProgress());
329 publishProgress(progress);
334 profile.storeTransaction(db, transaction);
335 matchedTransactionsCount = 0;
336 progress.setTotal(maxTransactionId);
339 state = ParserState.EXPECTING_TRANSACTION;
340 L(String.format("transaction %s saved → expecting transaction",
341 transaction.getId()));
342 transaction.finishLoading();
344 // sounds like a good idea, but transaction-1 may not be the first one chronologically
345 // for example, when you add the initial seeding transaction after entering some others
346 // if (transactionId == 1) {
347 // L("This was the initial transaction. Terminating " +
353 m = reTransactionDetails.matcher(line);
355 String acc_name = m.group(1);
356 String amount = m.group(2);
357 String currency = m.group(3);
358 if (currency == null) currency = "";
359 amount = amount.replace(',', '.');
360 transaction.addAccount(new LedgerTransactionAccount(acc_name,
361 Float.valueOf(amount), currency));
362 L(String.format(Locale.ENGLISH, "%d: %s = %s",
363 transaction.getId(), acc_name, amount));
365 else throw new IllegalStateException(
366 String.format("Can't parse transaction %d " + "details: %s",
367 transactionId, line));
371 throw new RuntimeException(
372 String.format("Unknown parser updating %s", state.name()));
378 profile.deleteNotPresentTransactions(db);
379 db.setTransactionSuccessful();
381 profile.setLastUpdateStamp();
390 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
391 db.execSQL("UPDATE transactions set keep=0 where profile=?",
392 new String[]{profile.getUuid()});
393 db.execSQL("update account_values set keep=0 where profile=?;",
394 new String[]{profile.getUuid()});
395 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
397 private boolean retrieveAccountList() throws IOException, HTTPException {
398 Progress progress = new Progress();
400 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
401 http.setAllowUserInteraction(false);
402 switch (http.getResponseCode()) {
408 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
410 publishProgress(progress);
411 SQLiteDatabase db = App.getDatabase();
412 ArrayList<LedgerAccount> accountList = new ArrayList<>();
413 boolean listFilledOK = false;
414 try (InputStream resp = http.getInputStream()) {
415 if (http.getResponseCode() != 200)
416 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
418 db.beginTransaction();
420 profile.markAccountsAsNotPresent(db);
422 AccountListParser parser = new AccountListParser(resp);
424 LedgerAccount prevAccount = null;
428 ParsedLedgerAccount parsedAccount = parser.nextAccount();
429 if (parsedAccount == null) break;
431 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
432 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
433 else acc.removeAmounts();
435 profile.storeAccount(db, acc);
436 String lastCurrency = null;
437 float lastCurrencyAmount = 0;
438 for (ParsedBalance b : parsedAccount.getAibalance()) {
439 final String currency = b.getAcommodity();
440 final float amount = b.getAquantity().asFloat();
441 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
443 if (lastCurrency != null) {
444 profile.storeAccountValue(db, acc.getName(), lastCurrency,
446 acc.addAmount(lastCurrencyAmount, lastCurrency);
448 lastCurrency = currency;
449 lastCurrencyAmount = amount;
452 if (lastCurrency != null) {
453 profile.storeAccountValue(db, acc.getName(), lastCurrency,
455 acc.addAmount(lastCurrencyAmount, lastCurrency);
458 if (acc.isVisible(accountList)) accountList.add(acc);
460 if (prevAccount != null) {
461 prevAccount.setHasSubAccounts(
462 acc.getName().startsWith(prevAccount.getName() + ":"));
469 profile.deleteNotPresentAccounts(db);
471 db.setTransactionSuccessful();
478 // should not be set in the DB transaction, because of a possible deadlock
479 // with the main and DbOpQueueRunner threads
480 if (listFilledOK) Data.accounts.setList(accountList);
484 private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
485 Progress progress = new Progress();
486 int maxTransactionId = Progress.INDETERMINATE;
488 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
489 http.setAllowUserInteraction(false);
490 publishProgress(progress);
491 switch (http.getResponseCode()) {
497 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
499 SQLiteDatabase db = App.getDatabase();
500 try (InputStream resp = http.getInputStream()) {
501 if (http.getResponseCode() != 200)
502 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
504 db.beginTransaction();
506 profile.markTransactionsAsNotPresent(db);
508 int matchedTransactionsCount = 0;
509 TransactionListParser parser = new TransactionListParser(resp);
511 int processedTransactionCount = 0;
513 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
514 int orderAccumulator = 0;
515 int lastTransactionId = 0;
519 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
521 if (parsedTransaction == null) break;
523 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
524 if (transaction.getId() > lastTransactionId) orderAccumulator++;
525 else orderAccumulator--;
526 lastTransactionId = transaction.getId();
527 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
528 if (orderAccumulator > 30) {
529 transactionOrder = DetectedTransactionOrder.FILE;
530 debug("rtt", String.format(Locale.ENGLISH,
531 "Detected native file order after %d transactions (factor %d)",
532 processedTransactionCount, orderAccumulator));
533 progress.setTotal(Data.transactions.size());
535 else if (orderAccumulator < -30) {
536 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
537 debug("rtt", String.format(Locale.ENGLISH,
538 "Detected reverse chronological order after %d transactions (factor %d)",
539 processedTransactionCount, orderAccumulator));
543 if (transaction.existsInDb(db)) {
544 profile.markTransactionAsPresent(db, transaction);
545 matchedTransactionsCount++;
547 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
548 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
550 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
551 progress.setTotal(progress.getProgress());
552 publishProgress(progress);
553 db.setTransactionSuccessful();
554 profile.setLastUpdateStamp();
559 profile.storeTransaction(db, transaction);
560 matchedTransactionsCount = 0;
561 progress.setTotal(maxTransactionId);
565 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
566 ((progress.getTotal() == Progress.INDETERMINATE) ||
567 (progress.getTotal() < transaction.getId())))
568 progress.setTotal(transaction.getId());
570 progress.setProgress(++processedTransactionCount);
571 publishProgress(progress);
575 profile.deleteNotPresentTransactions(db);
577 db.setTransactionSuccessful();
578 profile.setLastUpdateStamp();
588 @SuppressLint("DefaultLocale")
590 protected String doInBackground(Void... params) {
591 Data.backgroundTaskStarted();
593 if (!retrieveAccountList() || !retrieveTransactionList())
594 return retrieveTransactionListLegacy();
597 catch (MalformedURLException e) {
599 return "Invalid server URL";
601 catch (HTTPException e) {
603 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
605 catch (IOException e) {
607 return e.getLocalizedMessage();
609 catch (ParseException e) {
611 return "Network error";
613 catch (OperationCanceledException e) {
615 return "Operation cancelled";
618 Data.backgroundTaskFinished();
621 private MainActivity getContext() {
622 return contextRef.get();
624 private void throwIfCancelled() {
625 if (isCancelled()) throw new OperationCanceledException(null);
627 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
629 private enum ParserState {
630 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
631 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
634 public class Progress {
635 public static final int INDETERMINATE = -1;
636 private int progress;
639 this(INDETERMINATE, INDETERMINATE);
641 Progress(int progress, int total) {
642 this.progress = progress;
645 public int getProgress() {
648 protected void setProgress(int progress) {
649 this.progress = progress;
651 public int getTotal() {
654 protected void setTotal(int total) {
659 private class TransactionParserException extends IllegalStateException {
660 TransactionParserException(String message) {