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,
261 state = ParserState.EXPECTING_ACCOUNT;
262 L("→ expecting account");
267 case EXPECTING_TRANSACTION:
268 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
269 m = reTransactionStart.matcher(line);
271 transactionId = Integer.valueOf(m.group(1));
272 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
273 L(String.format(Locale.ENGLISH,
274 "found transaction %d → expecting description",
276 progress.setProgress(++processedTransactionCount);
277 if (maxTransactionId < transactionId)
278 maxTransactionId = transactionId;
279 if ((progress.getTotal() == Progress.INDETERMINATE) ||
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) == ' ')) continue;
293 m = reTransactionDescription.matcher(line);
295 if (transactionId == 0) throw new TransactionParserException(
296 "Transaction Id is 0 while expecting " + "description");
298 String date = m.group(1);
300 int equalsIndex = date.indexOf('=');
301 if (equalsIndex >= 0)
302 date = date.substring(equalsIndex + 1);
303 transaction = new LedgerTransaction(transactionId, date,
306 catch (ParseException e) {
308 return 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) →" +
313 " expecting details", transactionId, date, m.group(2)));
317 case EXPECTING_TRANSACTION_DETAILS:
318 if (line.isEmpty()) {
319 // transaction data collected
320 if (transaction.existsInDb(db)) {
321 profile.markTransactionAsPresent(db, transaction);
322 matchedTransactionsCount++;
324 if (matchedTransactionsCount ==
325 MATCHING_TRANSACTIONS_LIMIT)
327 profile.markTransactionsBeforeTransactionAsPresent(db,
329 progress.setTotal(progress.getProgress());
330 publishProgress(progress);
335 profile.storeTransaction(db, transaction);
336 matchedTransactionsCount = 0;
337 progress.setTotal(maxTransactionId);
340 state = ParserState.EXPECTING_TRANSACTION;
341 L(String.format("transaction %s saved → expecting transaction",
342 transaction.getId()));
343 transaction.finishLoading();
345 // sounds like a good idea, but transaction-1 may not be the first one chronologically
346 // for example, when you add the initial seeding transaction after entering some others
347 // if (transactionId == 1) {
348 // L("This was the initial transaction. Terminating " +
354 m = reTransactionDetails.matcher(line);
356 String acc_name = m.group(1);
357 String amount = m.group(2);
358 String currency = m.group(3);
359 if (currency == null) currency = "";
360 amount = amount.replace(',', '.');
361 transaction.addAccount(
362 new LedgerTransactionAccount(acc_name,
363 Float.valueOf(amount), currency));
364 L(String.format(Locale.ENGLISH, "%d: %s = %s",
365 transaction.getId(), acc_name, amount));
367 else throw new IllegalStateException(String.format(
368 "Can't parse transaction %d " + "details: %s",
369 transactionId, line));
373 throw new RuntimeException(
374 String.format("Unknown parser updating %s", state.name()));
380 profile.deleteNotPresentTransactions(db);
381 db.setTransactionSuccessful();
383 profile.setLastUpdateStamp();
393 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
394 db.execSQL("UPDATE transactions set keep=0 where profile=?",
395 new String[]{profile.getUuid()});
396 db.execSQL("update account_values set keep=0 where profile=?;",
397 new String[]{profile.getUuid()});
398 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
400 private boolean retrieveAccountList()
401 throws IOException, HTTPException {
402 Progress progress = new Progress();
404 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
405 http.setAllowUserInteraction(false);
406 switch (http.getResponseCode()) {
412 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
414 publishProgress(progress);
415 SQLiteDatabase db = MLDB.getDatabase();
416 ArrayList<LedgerAccount> accountList = new ArrayList<>();
417 boolean listFilledOK = false;
418 try (InputStream resp = http.getInputStream()) {
419 if (http.getResponseCode() != 200)
420 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
422 db.beginTransaction();
424 profile.markAccountsAsNotPresent(db);
426 AccountListParser parser = new AccountListParser(resp);
428 LedgerAccount prevAccount = null;
432 ParsedLedgerAccount parsedAccount = parser.nextAccount();
433 if (parsedAccount == null) break;
435 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
436 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
437 else acc.removeAmounts();
439 profile.storeAccount(db, acc);
440 String lastCurrency = null;
441 float lastCurrencyAmount = 0;
442 for (ParsedBalance b : parsedAccount.getAibalance()) {
443 final String currency = b.getAcommodity();
444 final float amount = b.getAquantity().asFloat();
445 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
447 if (lastCurrency != null) {
448 profile.storeAccountValue(db, acc.getName(), lastCurrency,
450 acc.addAmount(lastCurrencyAmount, lastCurrency);
452 lastCurrency = currency;
453 lastCurrencyAmount = amount;
456 if (lastCurrency != null) {
457 profile.storeAccountValue(db, acc.getName(), lastCurrency,
459 acc.addAmount(lastCurrencyAmount, lastCurrency);
462 if (acc.isVisible(accountList)) accountList.add(acc);
464 if (prevAccount != null) {
465 prevAccount.setHasSubAccounts(
466 acc.getName().startsWith(prevAccount.getName() + ":"));
473 profile.deleteNotPresentAccounts(db);
475 db.setTransactionSuccessful();
482 // should not be set in the DB transaction, because of a possible deadlock
483 // with the main and DbOpQueueRunner threads
484 if (listFilledOK) Data.accounts.setList(accountList);
488 private boolean retrieveTransactionList()
489 throws IOException, ParseException, HTTPException {
490 Progress progress = new Progress();
491 int maxTransactionId = Progress.INDETERMINATE;
493 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
494 http.setAllowUserInteraction(false);
495 publishProgress(progress);
496 switch (http.getResponseCode()) {
502 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
504 SQLiteDatabase db = MLDB.getDatabase();
505 try (InputStream resp = http.getInputStream()) {
506 if (http.getResponseCode() != 200)
507 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
509 db.beginTransaction();
511 profile.markTransactionsAsNotPresent(db);
513 int matchedTransactionsCount = 0;
514 TransactionListParser parser = new TransactionListParser(resp);
516 int processedTransactionCount = 0;
518 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
519 int orderAccumulator = 0;
520 int lastTransactionId = 0;
524 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
526 if (parsedTransaction == null) break;
528 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
529 if (transaction.getId() > lastTransactionId) orderAccumulator++;
530 else orderAccumulator--;
531 lastTransactionId = transaction.getId();
532 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
533 if (orderAccumulator > 30) {
534 transactionOrder = DetectedTransactionOrder.FILE;
535 debug("rtt", String.format(Locale.ENGLISH,
536 "Detected native file order after %d transactions (factor %d)",
537 processedTransactionCount, orderAccumulator));
538 progress.setTotal(Data.transactions.size());
540 else if (orderAccumulator < -30) {
541 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
542 debug("rtt", String.format(Locale.ENGLISH,
543 "Detected reverse chronological order after %d transactions (factor %d)",
544 processedTransactionCount, orderAccumulator));
548 if (transaction.existsInDb(db)) {
549 profile.markTransactionAsPresent(db, transaction);
550 matchedTransactionsCount++;
552 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
553 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
555 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
556 progress.setTotal(progress.getProgress());
557 publishProgress(progress);
558 db.setTransactionSuccessful();
559 profile.setLastUpdateStamp();
564 profile.storeTransaction(db, transaction);
565 matchedTransactionsCount = 0;
566 progress.setTotal(maxTransactionId);
570 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
571 ((progress.getTotal() == Progress.INDETERMINATE) ||
572 (progress.getTotal() < transaction.getId())))
573 progress.setTotal(transaction.getId());
575 progress.setProgress(++processedTransactionCount);
576 publishProgress(progress);
580 profile.deleteNotPresentTransactions(db);
582 db.setTransactionSuccessful();
583 profile.setLastUpdateStamp();
593 @SuppressLint("DefaultLocale")
595 protected String doInBackground(Void... params) {
596 Data.backgroundTaskStarted();
598 if (!retrieveAccountList() || !retrieveTransactionList())
599 return retrieveTransactionListLegacy();
602 catch (MalformedURLException e) {
604 return "Invalid server URL";
606 catch (HTTPException e) {
608 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
610 catch (IOException e) {
612 return e.getLocalizedMessage();
614 catch (ParseException e) {
616 return "Network error";
618 catch (OperationCanceledException e) {
620 return "Operation cancelled";
623 Data.backgroundTaskFinished();
626 private MainActivity getContext() {
627 return contextRef.get();
629 private void throwIfCancelled() {
630 if (isCancelled()) throw new OperationCanceledException(null);
632 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
634 private enum ParserState {
635 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
636 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
639 public class Progress {
640 public static final int INDETERMINATE = -1;
641 private int progress;
644 this(INDETERMINATE, INDETERMINATE);
646 Progress(int progress, int total) {
647 this.progress = progress;
650 public int getProgress() {
653 protected void setProgress(int progress) {
654 this.progress = progress;
656 public int getTotal() {
659 protected void setTotal(int total) {
664 private class TransactionParserException extends IllegalStateException {
665 TransactionParserException(String message) {