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.err.HTTPException;
26 import net.ktnx.mobileledger.json.AccountListParser;
27 import net.ktnx.mobileledger.json.ParsedBalance;
28 import net.ktnx.mobileledger.json.ParsedLedgerAccount;
29 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
30 import net.ktnx.mobileledger.json.TransactionListParser;
31 import net.ktnx.mobileledger.model.Data;
32 import net.ktnx.mobileledger.model.LedgerAccount;
33 import net.ktnx.mobileledger.model.LedgerTransaction;
34 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
35 import net.ktnx.mobileledger.model.MobileLedgerProfile;
36 import net.ktnx.mobileledger.ui.activity.MainActivity;
37 import net.ktnx.mobileledger.utils.MLDB;
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 static net.ktnx.mobileledger.utils.Logger.debug;
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("<tr class=\"title\" " +
65 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
66 private static final Pattern reTransactionDescription =
67 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
68 private static final Pattern reTransactionDetails =
69 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
70 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
71 private WeakReference<MainActivity> contextRef;
73 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
74 private Pattern reAccountValue = Pattern.compile(
75 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
76 private MobileLedgerProfile profile;
77 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
78 MobileLedgerProfile profile) {
79 this.contextRef = contextRef;
80 this.profile = profile;
82 private static void L(String msg) {
83 //debug("transaction-parser", msg);
86 protected void onProgressUpdate(Progress... values) {
87 super.onProgressUpdate(values);
88 MainActivity context = getContext();
89 if (context == null) return;
90 context.onRetrieveProgress(values[0]);
93 protected void onPreExecute() {
95 MainActivity context = getContext();
96 if (context == null) return;
97 context.onRetrieveStart();
100 protected void onPostExecute(String error) {
101 super.onPostExecute(error);
102 MainActivity context = getContext();
103 if (context == null) return;
104 context.onRetrieveDone(error);
107 protected void onCancelled() {
109 MainActivity context = getContext();
110 if (context == null) return;
111 context.onRetrieveDone(null);
113 private String retrieveTransactionListLegacy()
114 throws IOException, ParseException, HTTPException {
115 Progress progress = new Progress();
116 int maxTransactionId = Progress.INDETERMINATE;
117 ArrayList<LedgerAccount> accountList = new ArrayList<>();
118 HashMap<String, Void> accountNames = new HashMap<>();
119 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
120 LedgerAccount lastAccount = null, prevAccount = null;
121 boolean onlyStarred = Data.optShowOnlyStarred.get();
123 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
124 http.setAllowUserInteraction(false);
125 publishProgress(progress);
126 switch (http.getResponseCode()) {
130 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
132 try (SQLiteDatabase db = MLDB.getDatabase()) {
133 try (InputStream resp = http.getInputStream()) {
134 if (http.getResponseCode() != 200)
135 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
136 db.beginTransaction();
138 prepareDbForRetrieval(db, profile);
140 int matchedTransactionsCount = 0;
143 ParserState state = ParserState.EXPECTING_ACCOUNT;
146 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
148 int processedTransactionCount = 0;
149 int transactionId = 0;
150 LedgerTransaction transaction = null;
152 while ((line = buf.readLine()) != null) {
155 m = reComment.matcher(line);
157 // TODO: comments are ignored for now
158 // Log.v("transaction-parser", "Ignoring comment");
161 //L(String.format("State is %d", updating));
163 case EXPECTING_ACCOUNT:
164 if (line.equals("<h2>General Journal</h2>")) {
165 state = ParserState.EXPECTING_TRANSACTION;
166 L("→ expecting transaction");
167 // commit the current transaction and start a new one
168 // the account list in the UI should reflect the (committed)
169 // state of the database
170 db.setTransactionSuccessful();
172 Data.accounts.setList(accountList);
173 db.beginTransaction();
176 m = reAccountName.matcher(line);
178 String acct_encoded = m.group(1);
179 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
180 acct_name = acct_name.replace("\"", "");
181 L(String.format("found account: %s", acct_name));
183 prevAccount = lastAccount;
184 lastAccount = profile.tryLoadAccount(db, acct_name);
185 if (lastAccount == null)
186 lastAccount = new LedgerAccount(acct_name);
187 else lastAccount.removeAmounts();
188 profile.storeAccount(db, lastAccount);
190 if (prevAccount != null) prevAccount
191 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
192 // make sure the parent account(s) are present,
193 // synthesising them if necessary
194 // this happens when the (missing-in-HTML) parent account has
195 // only one child so we create a synthetic parent account record,
196 // copying the amounts when child's amounts are parsed
197 String parentName = lastAccount.getParentName();
198 if (parentName != null) {
199 Stack<String> toAppend = new Stack<>();
200 while (parentName != null) {
201 if (accountNames.containsKey(parentName)) break;
202 toAppend.push(parentName);
204 new LedgerAccount(parentName).getParentName();
206 syntheticAccounts.clear();
207 while (!toAppend.isEmpty()) {
208 String aName = toAppend.pop();
209 LedgerAccount acc = profile.tryLoadAccount(db, aName);
211 acc = new LedgerAccount(aName);
212 acc.setHiddenByStar(lastAccount.isHiddenByStar());
213 acc.setExpanded(!lastAccount.hasSubAccounts() ||
214 lastAccount.isExpanded());
216 acc.setHasSubAccounts(true);
217 acc.removeAmounts(); // filled below when amounts are parsed
218 if ((!onlyStarred || !acc.isHiddenByStar()) &&
219 acc.isVisible(accountList)) accountList.add(acc);
220 L(String.format("gap-filling with %s", aName));
221 accountNames.put(aName, null);
222 profile.storeAccount(db, acc);
223 syntheticAccounts.put(aName, acc);
227 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
228 lastAccount.isVisible(accountList))
229 accountList.add(lastAccount);
230 accountNames.put(acct_name, null);
232 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
233 L("→ expecting account amount");
237 case EXPECTING_ACCOUNT_AMOUNT:
238 m = reAccountValue.matcher(line);
239 boolean match_found = false;
244 String value = m.group(1);
245 String currency = m.group(2);
246 if (currency == null) currency = "";
247 value = value.replace(',', '.');
248 L("curr=" + currency + ", value=" + value);
249 final float val = Float.parseFloat(value);
250 profile.storeAccountValue(db, lastAccount.getName(), currency,
252 lastAccount.addAmount(val, currency);
253 for (LedgerAccount syn : syntheticAccounts.values()) {
254 syn.addAmount(val, currency);
255 profile.storeAccountValue(db, syn.getName(), currency, val);
260 state = ParserState.EXPECTING_ACCOUNT;
261 L("→ expecting account");
266 case EXPECTING_TRANSACTION:
267 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
268 m = reTransactionStart.matcher(line);
270 transactionId = Integer.valueOf(m.group(1));
271 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
272 L(String.format(Locale.ENGLISH,
273 "found transaction %d → expecting description",
275 progress.setProgress(++processedTransactionCount);
276 if (maxTransactionId < transactionId)
277 maxTransactionId = transactionId;
278 if ((progress.getTotal() == Progress.INDETERMINATE) ||
279 (progress.getTotal() < transactionId))
280 progress.setTotal(transactionId);
281 publishProgress(progress);
283 m = reEnd.matcher(line);
285 L("--- transaction value complete ---");
290 case EXPECTING_TRANSACTION_DESCRIPTION:
291 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
292 m = reTransactionDescription.matcher(line);
294 if (transactionId == 0) throw new TransactionParserException(
295 "Transaction Id is 0 while expecting " + "description");
297 String date = m.group(1);
299 int equalsIndex = date.indexOf('=');
300 if (equalsIndex >= 0)
301 date = date.substring(equalsIndex + 1);
302 transaction = new LedgerTransaction(transactionId, date,
305 catch (ParseException e) {
307 return 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) →" +
312 " expecting details", transactionId, date, m.group(2)));
316 case EXPECTING_TRANSACTION_DETAILS:
317 if (line.isEmpty()) {
318 // transaction data collected
319 if (transaction.existsInDb(db)) {
320 profile.markTransactionAsPresent(db, transaction);
321 matchedTransactionsCount++;
323 if (matchedTransactionsCount ==
324 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(
361 new LedgerTransactionAccount(acc_name,
362 Float.valueOf(amount), currency));
363 L(String.format(Locale.ENGLISH, "%d: %s = %s",
364 transaction.getId(), acc_name, amount));
366 else throw new IllegalStateException(String.format(
367 "Can't parse transaction %d " + "details: %s",
368 transactionId, line));
372 throw new RuntimeException(
373 String.format("Unknown parser updating %s", state.name()));
379 profile.deleteNotPresentTransactions(db);
380 db.setTransactionSuccessful();
382 profile.setLastUpdateStamp();
392 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
393 db.execSQL("UPDATE transactions set keep=0 where profile=?",
394 new String[]{profile.getUuid()});
395 db.execSQL("update account_values set keep=0 where profile=?;",
396 new String[]{profile.getUuid()});
397 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
399 private boolean retrieveAccountList()
400 throws IOException, HTTPException {
401 Progress progress = new Progress();
403 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
404 http.setAllowUserInteraction(false);
405 switch (http.getResponseCode()) {
411 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
413 publishProgress(progress);
414 SQLiteDatabase db = MLDB.getDatabase();
415 ArrayList<LedgerAccount> accountList = new ArrayList<>();
416 boolean listFilledOK = false;
417 try (InputStream resp = http.getInputStream()) {
418 if (http.getResponseCode() != 200)
419 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
421 db.beginTransaction();
423 profile.markAccountsAsNotPresent(db);
425 AccountListParser parser = new AccountListParser(resp);
427 LedgerAccount prevAccount = null;
431 ParsedLedgerAccount parsedAccount = parser.nextAccount();
432 if (parsedAccount == null) break;
434 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
435 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
436 else acc.removeAmounts();
438 profile.storeAccount(db, acc);
439 String lastCurrency = null;
440 float lastCurrencyAmount = 0;
441 for (ParsedBalance b : parsedAccount.getAibalance()) {
442 final String currency = b.getAcommodity();
443 final float amount = b.getAquantity().asFloat();
444 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
446 if (lastCurrency != null) {
447 profile.storeAccountValue(db, acc.getName(), lastCurrency,
449 acc.addAmount(lastCurrencyAmount, lastCurrency);
451 lastCurrency = currency;
452 lastCurrencyAmount = amount;
455 if (lastCurrency != null) {
456 profile.storeAccountValue(db, acc.getName(), lastCurrency,
458 acc.addAmount(lastCurrencyAmount, lastCurrency);
461 if (acc.isVisible(accountList)) accountList.add(acc);
463 if (prevAccount != null) {
464 prevAccount.setHasSubAccounts(
465 acc.getName().startsWith(prevAccount.getName() + ":"));
472 profile.deleteNotPresentAccounts(db);
474 db.setTransactionSuccessful();
481 // should not be set in the DB transaction, because of a possible deadlock
482 // with the main and DbOpQueueRunner threads
483 if (listFilledOK) Data.accounts.setList(accountList);
487 private boolean retrieveTransactionList()
488 throws IOException, ParseException, HTTPException {
489 Progress progress = new Progress();
490 int maxTransactionId = Progress.INDETERMINATE;
492 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
493 http.setAllowUserInteraction(false);
494 publishProgress(progress);
495 switch (http.getResponseCode()) {
501 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
503 SQLiteDatabase db = MLDB.getDatabase();
504 try (InputStream resp = http.getInputStream()) {
505 if (http.getResponseCode() != 200)
506 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
508 db.beginTransaction();
510 profile.markTransactionsAsNotPresent(db);
512 int matchedTransactionsCount = 0;
513 TransactionListParser parser = new TransactionListParser(resp);
515 int processedTransactionCount = 0;
517 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
518 int orderAccumulator = 0;
519 int lastTransactionId = 0;
523 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
525 if (parsedTransaction == null) break;
527 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
528 if (transaction.getId() > lastTransactionId) orderAccumulator++;
529 else orderAccumulator--;
530 lastTransactionId = transaction.getId();
531 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
532 if (orderAccumulator > 30) {
533 transactionOrder = DetectedTransactionOrder.FILE;
534 debug("rtt", String.format(Locale.ENGLISH,
535 "Detected native file order after %d transactions (factor %d)",
536 processedTransactionCount, orderAccumulator));
537 progress.setTotal(Data.transactions.size());
539 else if (orderAccumulator < -30) {
540 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
541 debug("rtt", String.format(Locale.ENGLISH,
542 "Detected reverse chronological order after %d transactions (factor %d)",
543 processedTransactionCount, orderAccumulator));
547 if (transaction.existsInDb(db)) {
548 profile.markTransactionAsPresent(db, transaction);
549 matchedTransactionsCount++;
551 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
552 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
554 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
555 progress.setTotal(progress.getProgress());
556 publishProgress(progress);
557 db.setTransactionSuccessful();
558 profile.setLastUpdateStamp();
563 profile.storeTransaction(db, transaction);
564 matchedTransactionsCount = 0;
565 progress.setTotal(maxTransactionId);
569 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
570 ((progress.getTotal() == Progress.INDETERMINATE) ||
571 (progress.getTotal() < transaction.getId())))
572 progress.setTotal(transaction.getId());
574 progress.setProgress(++processedTransactionCount);
575 publishProgress(progress);
579 profile.deleteNotPresentTransactions(db);
581 db.setTransactionSuccessful();
582 profile.setLastUpdateStamp();
592 @SuppressLint("DefaultLocale")
594 protected String doInBackground(Void... params) {
595 Data.backgroundTaskStarted();
597 if (!retrieveAccountList() || !retrieveTransactionList())
598 return retrieveTransactionListLegacy();
601 catch (MalformedURLException e) {
603 return "Invalid server URL";
605 catch (HTTPException e) {
607 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
609 catch (IOException e) {
611 return e.getLocalizedMessage();
613 catch (ParseException e) {
615 return "Network error";
617 catch (OperationCanceledException e) {
619 return "Operation cancelled";
622 Data.backgroundTaskFinished();
625 private MainActivity getContext() {
626 return contextRef.get();
628 private void throwIfCancelled() {
629 if (isCancelled()) throw new OperationCanceledException(null);
631 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
633 private enum ParserState {
634 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
635 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
638 public class Progress {
639 public static final int INDETERMINATE = -1;
640 private int progress;
643 this(INDETERMINATE, INDETERMINATE);
645 Progress(int progress, int total) {
646 this.progress = progress;
649 public int getProgress() {
652 protected void setProgress(int progress) {
653 this.progress = progress;
655 public int getTotal() {
658 protected void setTotal(int total) {
663 private class TransactionParserException extends IllegalStateException {
664 TransactionParserException(String message) {