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 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
77 this.contextRef = contextRef;
79 private static void L(String msg) {
80 //debug("transaction-parser", msg);
83 protected void onProgressUpdate(Progress... values) {
84 super.onProgressUpdate(values);
85 MainActivity context = getContext();
86 if (context == null) return;
87 context.onRetrieveProgress(values[0]);
90 protected void onPreExecute() {
92 MainActivity context = getContext();
93 if (context == null) return;
94 context.onRetrieveStart();
97 protected void onPostExecute(String error) {
98 super.onPostExecute(error);
99 MainActivity context = getContext();
100 if (context == null) return;
101 context.onRetrieveDone(error);
104 protected void onCancelled() {
106 MainActivity context = getContext();
107 if (context == null) return;
108 context.onRetrieveDone(null);
110 private String retrieveTransactionListLegacy(MobileLedgerProfile profile)
111 throws IOException, ParseException, HTTPException {
112 Progress progress = new Progress();
113 int maxTransactionId = Progress.INDETERMINATE;
114 ArrayList<LedgerAccount> accountList = new ArrayList<>();
115 HashMap<String, Void> accountNames = new HashMap<>();
116 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
117 LedgerAccount lastAccount = null, prevAccount = null;
118 boolean onlyStarred = Data.optShowOnlyStarred.get();
120 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
121 http.setAllowUserInteraction(false);
122 publishProgress(progress);
123 switch (http.getResponseCode()) {
127 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
129 try (SQLiteDatabase db = MLDB.getDatabase()) {
130 try (InputStream resp = http.getInputStream()) {
131 if (http.getResponseCode() != 200)
132 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
133 db.beginTransaction();
135 prepareDbForRetrieval(db, profile);
137 int matchedTransactionsCount = 0;
140 ParserState state = ParserState.EXPECTING_ACCOUNT;
143 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
145 int processedTransactionCount = 0;
146 int transactionId = 0;
147 LedgerTransaction transaction = null;
149 while ((line = buf.readLine()) != null) {
152 m = reComment.matcher(line);
154 // TODO: comments are ignored for now
155 // Log.v("transaction-parser", "Ignoring comment");
158 //L(String.format("State is %d", updating));
160 case EXPECTING_ACCOUNT:
161 if (line.equals("<h2>General Journal</h2>")) {
162 state = ParserState.EXPECTING_TRANSACTION;
163 L("→ expecting transaction");
164 // commit the current transaction and start a new one
165 // the account list in the UI should reflect the (committed)
166 // state of the database
167 db.setTransactionSuccessful();
169 Data.accounts.setList(accountList);
170 db.beginTransaction();
173 m = reAccountName.matcher(line);
175 String acct_encoded = m.group(1);
176 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
177 acct_name = acct_name.replace("\"", "");
178 L(String.format("found account: %s", acct_name));
180 prevAccount = lastAccount;
181 lastAccount = profile.tryLoadAccount(db, acct_name);
182 if (lastAccount == null)
183 lastAccount = new LedgerAccount(acct_name);
184 else lastAccount.removeAmounts();
185 profile.storeAccount(db, lastAccount);
187 if (prevAccount != null) prevAccount
188 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
189 // make sure the parent account(s) are present,
190 // synthesising them if necessary
191 // this happens when the (missing-in-HTML) parent account has
192 // only one child so we create a synthetic parent account record,
193 // copying the amounts when child's amounts are parsed
194 String parentName = lastAccount.getParentName();
195 if (parentName != null) {
196 Stack<String> toAppend = new Stack<>();
197 while (parentName != null) {
198 if (accountNames.containsKey(parentName)) break;
199 toAppend.push(parentName);
201 new LedgerAccount(parentName).getParentName();
203 syntheticAccounts.clear();
204 while (!toAppend.isEmpty()) {
205 String aName = toAppend.pop();
206 LedgerAccount acc = profile.tryLoadAccount(db, aName);
208 acc = new LedgerAccount(aName);
209 acc.setHiddenByStar(lastAccount.isHiddenByStar());
210 acc.setExpanded(!lastAccount.hasSubAccounts() ||
211 lastAccount.isExpanded());
213 acc.setHasSubAccounts(true);
214 acc.removeAmounts(); // filled below when amounts are parsed
215 if ((!onlyStarred || !acc.isHiddenByStar()) &&
216 acc.isVisible(accountList)) accountList.add(acc);
217 L(String.format("gap-filling with %s", aName));
218 accountNames.put(aName, null);
219 profile.storeAccount(db, acc);
220 syntheticAccounts.put(aName, acc);
224 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
225 lastAccount.isVisible(accountList))
226 accountList.add(lastAccount);
227 accountNames.put(acct_name, null);
229 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
230 L("→ expecting account amount");
234 case EXPECTING_ACCOUNT_AMOUNT:
235 m = reAccountValue.matcher(line);
236 boolean match_found = false;
241 String value = m.group(1);
242 String currency = m.group(2);
243 if (currency == null) currency = "";
244 value = value.replace(',', '.');
245 L("curr=" + currency + ", value=" + value);
246 final float val = Float.parseFloat(value);
247 profile.storeAccountValue(db, lastAccount.getName(), currency,
249 lastAccount.addAmount(val, currency);
250 for (LedgerAccount syn : syntheticAccounts.values()) {
251 syn.addAmount(val, currency);
252 profile.storeAccountValue(db, syn.getName(), currency, val);
257 state = ParserState.EXPECTING_ACCOUNT;
258 L("→ expecting account");
263 case EXPECTING_TRANSACTION:
264 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
265 m = reTransactionStart.matcher(line);
267 transactionId = Integer.valueOf(m.group(1));
268 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
269 L(String.format(Locale.ENGLISH,
270 "found transaction %d → expecting description",
272 progress.setProgress(++processedTransactionCount);
273 if (maxTransactionId < transactionId)
274 maxTransactionId = transactionId;
275 if ((progress.getTotal() == Progress.INDETERMINATE) ||
276 (progress.getTotal() < transactionId))
277 progress.setTotal(transactionId);
278 publishProgress(progress);
280 m = reEnd.matcher(line);
282 L("--- transaction value complete ---");
287 case EXPECTING_TRANSACTION_DESCRIPTION:
288 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
289 m = reTransactionDescription.matcher(line);
291 if (transactionId == 0) throw new TransactionParserException(
292 "Transaction Id is 0 while expecting " + "description");
294 String date = m.group(1);
296 int equalsIndex = date.indexOf('=');
297 if (equalsIndex >= 0)
298 date = date.substring(equalsIndex + 1);
299 transaction = new LedgerTransaction(transactionId, date,
302 catch (ParseException e) {
304 return String.format("Error parsing date '%s'", date);
306 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
307 L(String.format(Locale.ENGLISH,
308 "transaction %d created for %s (%s) →" +
309 " expecting details", transactionId, date, m.group(2)));
313 case EXPECTING_TRANSACTION_DETAILS:
314 if (line.isEmpty()) {
315 // transaction data collected
316 if (transaction.existsInDb(db)) {
317 profile.markTransactionAsPresent(db, transaction);
318 matchedTransactionsCount++;
320 if (matchedTransactionsCount ==
321 MATCHING_TRANSACTIONS_LIMIT)
323 profile.markTransactionsBeforeTransactionAsPresent(db,
325 progress.setTotal(progress.getProgress());
326 publishProgress(progress);
331 profile.storeTransaction(db, transaction);
332 matchedTransactionsCount = 0;
333 progress.setTotal(maxTransactionId);
336 state = ParserState.EXPECTING_TRANSACTION;
337 L(String.format("transaction %s saved → expecting transaction",
338 transaction.getId()));
339 transaction.finishLoading();
341 // sounds like a good idea, but transaction-1 may not be the first one chronologically
342 // for example, when you add the initial seeding transaction after entering some others
343 // if (transactionId == 1) {
344 // L("This was the initial transaction. Terminating " +
350 m = reTransactionDetails.matcher(line);
352 String acc_name = m.group(1);
353 String amount = m.group(2);
354 String currency = m.group(3);
355 if (currency == null) currency = "";
356 amount = amount.replace(',', '.');
357 transaction.addAccount(
358 new LedgerTransactionAccount(acc_name,
359 Float.valueOf(amount), currency));
360 L(String.format(Locale.ENGLISH, "%d: %s = %s",
361 transaction.getId(), acc_name, amount));
363 else throw new IllegalStateException(String.format(
364 "Can't parse transaction %d " + "details: %s",
365 transactionId, line));
369 throw new RuntimeException(
370 String.format("Unknown parser updating %s", state.name()));
376 profile.deleteNotPresentTransactions(db);
377 db.setTransactionSuccessful();
379 profile.setLastUpdateStamp();
389 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
390 db.execSQL("UPDATE transactions set keep=0 where profile=?",
391 new String[]{profile.getUuid()});
392 db.execSQL("update account_values set keep=0 where profile=?;",
393 new String[]{profile.getUuid()});
394 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
396 private boolean retrieveAccountList(MobileLedgerProfile profile)
397 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 = MLDB.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(MobileLedgerProfile profile)
485 throws IOException, ParseException, HTTPException {
486 Progress progress = new Progress();
487 int maxTransactionId = Progress.INDETERMINATE;
489 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
490 http.setAllowUserInteraction(false);
491 publishProgress(progress);
492 switch (http.getResponseCode()) {
498 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
500 SQLiteDatabase db = MLDB.getDatabase();
501 try (InputStream resp = http.getInputStream()) {
502 if (http.getResponseCode() != 200)
503 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
505 db.beginTransaction();
507 profile.markTransactionsAsNotPresent(db);
509 int matchedTransactionsCount = 0;
510 TransactionListParser parser = new TransactionListParser(resp);
512 int processedTransactionCount = 0;
514 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
515 int orderAccumulator = 0;
516 int lastTransactionId = 0;
520 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
522 if (parsedTransaction == null) break;
524 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
525 if (transaction.getId() > lastTransactionId) orderAccumulator++;
526 else orderAccumulator--;
527 lastTransactionId = transaction.getId();
528 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
529 if (orderAccumulator > 30) {
530 transactionOrder = DetectedTransactionOrder.FILE;
531 debug("rtt", String.format(Locale.ENGLISH,
532 "Detected native file order after %d transactions (factor %d)",
533 processedTransactionCount, orderAccumulator));
534 progress.setTotal(Data.transactions.size());
536 else if (orderAccumulator < -30) {
537 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
538 debug("rtt", String.format(Locale.ENGLISH,
539 "Detected reverse chronological order after %d transactions (factor %d)",
540 processedTransactionCount, orderAccumulator));
544 if (transaction.existsInDb(db)) {
545 profile.markTransactionAsPresent(db, transaction);
546 matchedTransactionsCount++;
548 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
549 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
551 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
552 progress.setTotal(progress.getProgress());
553 publishProgress(progress);
554 db.setTransactionSuccessful();
555 profile.setLastUpdateStamp();
560 profile.storeTransaction(db, transaction);
561 matchedTransactionsCount = 0;
562 progress.setTotal(maxTransactionId);
566 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
567 ((progress.getTotal() == Progress.INDETERMINATE) ||
568 (progress.getTotal() < transaction.getId())))
569 progress.setTotal(transaction.getId());
571 progress.setProgress(++processedTransactionCount);
572 publishProgress(progress);
576 profile.deleteNotPresentTransactions(db);
578 db.setTransactionSuccessful();
579 profile.setLastUpdateStamp();
589 @SuppressLint("DefaultLocale")
591 protected String doInBackground(Void... params) {
592 MobileLedgerProfile profile = Data.profile.get();
593 Data.backgroundTaskStarted();
595 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
596 return retrieveTransactionListLegacy(profile);
599 catch (MalformedURLException e) {
601 return "Invalid server URL";
603 catch (HTTPException e) {
605 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
607 catch (IOException e) {
609 return e.getLocalizedMessage();
611 catch (ParseException e) {
613 return "Network error";
615 catch (OperationCanceledException e) {
617 return "Operation cancelled";
620 Data.backgroundTaskFinished();
623 private MainActivity getContext() {
624 return contextRef.get();
626 private void throwIfCancelled() {
627 if (isCancelled()) throw new OperationCanceledException(null);
629 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
631 private enum ParserState {
632 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
633 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
636 public class Progress {
637 public static final int INDETERMINATE = -1;
638 private int progress;
641 this(INDETERMINATE, INDETERMINATE);
643 Progress(int progress, int total) {
644 this.progress = progress;
647 public int getProgress() {
650 protected void setProgress(int progress) {
651 this.progress = progress;
653 public int getTotal() {
656 protected void setTotal(int total) {
661 private class TransactionParserException extends IllegalStateException {
662 TransactionParserException(String message) {