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;
24 import android.util.Log;
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.MLDB;
39 import net.ktnx.mobileledger.utils.NetworkUtil;
41 import java.io.BufferedReader;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.InputStreamReader;
45 import java.lang.ref.WeakReference;
46 import java.net.HttpURLConnection;
47 import java.net.MalformedURLException;
48 import java.net.URLDecoder;
49 import java.nio.charset.StandardCharsets;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.HashMap;
53 import java.util.Locale;
54 import java.util.Stack;
55 import java.util.regex.Matcher;
56 import java.util.regex.Pattern;
58 import static net.ktnx.mobileledger.utils.Logger.debug;
61 public class RetrieveTransactionsTask
62 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
63 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
64 private static final Pattern reComment = Pattern.compile("^\\s*;");
65 private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
66 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
67 private static final Pattern reTransactionDescription =
68 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
69 private static final Pattern reTransactionDetails =
70 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
71 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
72 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 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
79 this.contextRef = contextRef;
81 private static void L(String msg) {
82 //debug("transaction-parser", msg);
85 protected void onProgressUpdate(Progress... values) {
86 super.onProgressUpdate(values);
87 MainActivity context = getContext();
88 if (context == null) return;
89 context.onRetrieveProgress(values[0]);
92 protected void onPreExecute() {
94 MainActivity context = getContext();
95 if (context == null) return;
96 context.onRetrieveStart();
99 protected void onPostExecute(String error) {
100 super.onPostExecute(error);
101 MainActivity context = getContext();
102 if (context == null) return;
103 context.onRetrieveDone(error);
106 protected void onCancelled() {
108 MainActivity context = getContext();
109 if (context == null) return;
110 context.onRetrieveDone(null);
112 private String retrieveTransactionListLegacy(MobileLedgerProfile profile)
113 throws IOException, ParseException, HTTPException {
114 Progress progress = new Progress();
115 int maxTransactionId = Progress.INDETERMINATE;
116 ArrayList<LedgerAccount> accountList = new ArrayList<>();
117 HashMap<String, Void> accountNames = new HashMap<>();
118 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
119 LedgerAccount lastAccount = null, prevAccount = null;
120 boolean onlyStarred = Data.optShowOnlyStarred.get();
122 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
123 http.setAllowUserInteraction(false);
124 publishProgress(progress);
125 switch (http.getResponseCode()) {
129 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
131 try (SQLiteDatabase db = MLDB.getDatabase()) {
132 try (InputStream resp = http.getInputStream()) {
133 if (http.getResponseCode() != 200)
134 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
135 db.beginTransaction();
137 prepareDbForRetrieval(db, profile);
139 int matchedTransactionsCount = 0;
142 ParserState state = ParserState.EXPECTING_ACCOUNT;
145 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
147 int processedTransactionCount = 0;
148 int transactionId = 0;
149 LedgerTransaction transaction = null;
151 while ((line = buf.readLine()) != null) {
154 m = reComment.matcher(line);
156 // TODO: comments are ignored for now
157 Log.v("transaction-parser", "Ignoring comment");
160 //L(String.format("State is %d", updating));
162 case EXPECTING_ACCOUNT:
163 if (line.equals("<h2>General Journal</h2>")) {
164 state = ParserState.EXPECTING_TRANSACTION;
165 L("→ expecting transaction");
166 // commit the current transaction and start a new one
167 // the account list in the UI should reflect the (committed)
168 // state of the database
169 db.setTransactionSuccessful();
171 Data.accounts.setList(accountList);
172 db.beginTransaction();
175 m = reAccountName.matcher(line);
177 String acct_encoded = m.group(1);
178 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
179 acct_name = acct_name.replace("\"", "");
180 L(String.format("found account: %s", acct_name));
182 prevAccount = lastAccount;
183 lastAccount = profile.tryLoadAccount(db, acct_name);
184 if (lastAccount == null)
185 lastAccount = new LedgerAccount(acct_name);
186 else lastAccount.removeAmounts();
187 profile.storeAccount(db, lastAccount);
189 if (prevAccount != null) prevAccount
190 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
191 // make sure the parent account(s) are present,
192 // synthesising them if necessary
193 // this happens when the (missing-in-HTML) parent account has
194 // only one child so we create a synthetic parent account record,
195 // copying the amounts when child's amounts are parsed
196 String parentName = lastAccount.getParentName();
197 if (parentName != null) {
198 Stack<String> toAppend = new Stack<>();
199 while (parentName != null) {
200 if (accountNames.containsKey(parentName)) break;
201 toAppend.push(parentName);
203 new LedgerAccount(parentName).getParentName();
205 syntheticAccounts.clear();
206 while (!toAppend.isEmpty()) {
207 String aName = toAppend.pop();
208 LedgerAccount acc = profile.tryLoadAccount(db, aName);
210 acc = new LedgerAccount(aName);
211 acc.setHiddenByStar(lastAccount.isHiddenByStar());
212 acc.setExpanded(!lastAccount.hasSubAccounts() ||
213 lastAccount.isExpanded());
215 acc.setHasSubAccounts(true);
216 acc.removeAmounts(); // filled below when amounts are parsed
217 if ((!onlyStarred || !acc.isHiddenByStar()) &&
218 acc.isVisible(accountList)) accountList.add(acc);
219 L(String.format("gap-filling with %s", aName));
220 accountNames.put(aName, null);
221 profile.storeAccount(db, acc);
222 syntheticAccounts.put(aName, acc);
226 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
227 lastAccount.isVisible(accountList))
228 accountList.add(lastAccount);
229 accountNames.put(acct_name, null);
231 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
232 L("→ expecting account amount");
236 case EXPECTING_ACCOUNT_AMOUNT:
237 m = reAccountValue.matcher(line);
238 boolean match_found = false;
243 String value = m.group(1);
244 String currency = m.group(2);
245 if (currency == null) currency = "";
246 value = value.replace(',', '.');
247 L("curr=" + currency + ", value=" + value);
248 final float val = Float.parseFloat(value);
249 profile.storeAccountValue(db, lastAccount.getName(), currency,
251 lastAccount.addAmount(val, currency);
252 for (LedgerAccount syn : syntheticAccounts.values()) {
253 syn.addAmount(val, currency);
254 profile.storeAccountValue(db, syn.getName(), currency, val);
259 state = ParserState.EXPECTING_ACCOUNT;
260 L("→ expecting account");
265 case EXPECTING_TRANSACTION:
266 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
267 m = reTransactionStart.matcher(line);
269 transactionId = Integer.valueOf(m.group(1));
270 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
271 L(String.format(Locale.ENGLISH,
272 "found transaction %d → expecting description",
274 progress.setProgress(++processedTransactionCount);
275 if (maxTransactionId < transactionId)
276 maxTransactionId = transactionId;
277 if ((progress.getTotal() == Progress.INDETERMINATE) ||
278 (progress.getTotal() < transactionId))
279 progress.setTotal(transactionId);
280 publishProgress(progress);
282 m = reEnd.matcher(line);
284 L("--- transaction value complete ---");
289 case EXPECTING_TRANSACTION_DESCRIPTION:
290 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
291 m = reTransactionDescription.matcher(line);
293 if (transactionId == 0) throw new TransactionParserException(
294 "Transaction Id is 0 while expecting " + "description");
296 String date = m.group(1);
298 int equalsIndex = date.indexOf('=');
299 if (equalsIndex >= 0)
300 date = date.substring(equalsIndex + 1);
301 transaction = new LedgerTransaction(transactionId, date,
304 catch (ParseException e) {
306 return String.format("Error parsing date '%s'", date);
308 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
309 L(String.format(Locale.ENGLISH,
310 "transaction %d created for %s (%s) →" +
311 " expecting details", transactionId, date, m.group(2)));
315 case EXPECTING_TRANSACTION_DETAILS:
316 if (line.isEmpty()) {
317 // transaction data collected
318 if (transaction.existsInDb(db)) {
319 profile.markTransactionAsPresent(db, transaction);
320 matchedTransactionsCount++;
322 if (matchedTransactionsCount ==
323 MATCHING_TRANSACTIONS_LIMIT)
325 profile.markTransactionsBeforeTransactionAsPresent(db,
327 progress.setTotal(progress.getProgress());
328 publishProgress(progress);
333 profile.storeTransaction(db, transaction);
334 matchedTransactionsCount = 0;
335 progress.setTotal(maxTransactionId);
338 state = ParserState.EXPECTING_TRANSACTION;
339 L(String.format("transaction %s saved → expecting transaction",
340 transaction.getId()));
341 transaction.finishLoading();
343 // sounds like a good idea, but transaction-1 may not be the first one chronologically
344 // for example, when you add the initial seeding transaction after entering some others
345 // if (transactionId == 1) {
346 // L("This was the initial transaction. Terminating " +
352 m = reTransactionDetails.matcher(line);
354 String acc_name = m.group(1);
355 String amount = m.group(2);
356 String currency = m.group(3);
357 if (currency == null) currency = "";
358 amount = amount.replace(',', '.');
359 transaction.addAccount(
360 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(String.format(
366 "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();
391 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
392 db.execSQL("UPDATE transactions set keep=0 where profile=?",
393 new String[]{profile.getUuid()});
394 db.execSQL("update account_values set keep=0 where profile=?;",
395 new String[]{profile.getUuid()});
396 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
398 private boolean retrieveAccountList(MobileLedgerProfile profile)
399 throws IOException, HTTPException {
400 Progress progress = new Progress();
402 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
403 http.setAllowUserInteraction(false);
404 switch (http.getResponseCode()) {
410 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
412 publishProgress(progress);
413 SQLiteDatabase db = MLDB.getDatabase();
414 ArrayList<LedgerAccount> accountList = new ArrayList<>();
415 boolean listFilledOK = false;
416 try (InputStream resp = http.getInputStream()) {
417 if (http.getResponseCode() != 200)
418 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
420 db.beginTransaction();
422 profile.markAccountsAsNotPresent(db);
424 AccountListParser parser = new AccountListParser(resp);
426 LedgerAccount prevAccount = null;
430 ParsedLedgerAccount parsedAccount = parser.nextAccount();
431 if (parsedAccount == null) break;
433 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
434 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
435 else acc.removeAmounts();
437 profile.storeAccount(db, acc);
438 String lastCurrency = null;
439 float lastCurrencyAmount = 0;
440 for (ParsedBalance b : parsedAccount.getAibalance()) {
441 final String currency = b.getAcommodity();
442 final float amount = b.getAquantity().asFloat();
443 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
445 if (lastCurrency != null) {
446 profile.storeAccountValue(db, acc.getName(), lastCurrency,
448 acc.addAmount(lastCurrencyAmount, lastCurrency);
450 lastCurrency = currency;
451 lastCurrencyAmount = amount;
454 if (lastCurrency != null) {
455 profile.storeAccountValue(db, acc.getName(), lastCurrency,
457 acc.addAmount(lastCurrencyAmount, lastCurrency);
460 if (acc.isVisible(accountList)) accountList.add(acc);
462 if (prevAccount != null) {
463 prevAccount.setHasSubAccounts(
464 acc.getName().startsWith(prevAccount.getName() + ":"));
471 profile.deleteNotPresentAccounts(db);
473 db.setTransactionSuccessful();
480 // should not be set in the DB transaction, because of a possible deadlock
481 // with the main and DbOpQueueRunner threads
482 if (listFilledOK) Data.accounts.setList(accountList);
486 private boolean retrieveTransactionList(MobileLedgerProfile profile)
487 throws IOException, ParseException, HTTPException {
488 Progress progress = new Progress();
489 int maxTransactionId = Progress.INDETERMINATE;
491 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
492 http.setAllowUserInteraction(false);
493 publishProgress(progress);
494 switch (http.getResponseCode()) {
500 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
502 SQLiteDatabase db = MLDB.getDatabase();
503 try (InputStream resp = http.getInputStream()) {
504 if (http.getResponseCode() != 200)
505 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
507 db.beginTransaction();
509 profile.markTransactionsAsNotPresent(db);
511 int matchedTransactionsCount = 0;
512 TransactionListParser parser = new TransactionListParser(resp);
514 int processedTransactionCount = 0;
516 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
517 int orderAccumulator = 0;
518 int lastTransactionId = 0;
522 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
524 if (parsedTransaction == null) break;
526 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
527 if (transaction.getId() > lastTransactionId) orderAccumulator++;
528 else orderAccumulator--;
529 lastTransactionId = transaction.getId();
530 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
531 if (orderAccumulator > 30) {
532 transactionOrder = DetectedTransactionOrder.FILE;
533 debug("rtt", String.format(Locale.ENGLISH,
534 "Detected native file order after %d transactions (factor %d)",
535 processedTransactionCount, orderAccumulator));
536 progress.setTotal(Data.transactions.size());
538 else if (orderAccumulator < -30) {
539 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
540 debug("rtt", String.format(Locale.ENGLISH,
541 "Detected reverse chronological order after %d transactions (factor %d)",
542 processedTransactionCount, orderAccumulator));
546 if (transaction.existsInDb(db)) {
547 profile.markTransactionAsPresent(db, transaction);
548 matchedTransactionsCount++;
550 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
551 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
553 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
554 progress.setTotal(progress.getProgress());
555 publishProgress(progress);
556 db.setTransactionSuccessful();
557 profile.setLastUpdateStamp();
562 profile.storeTransaction(db, transaction);
563 matchedTransactionsCount = 0;
564 progress.setTotal(maxTransactionId);
568 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
569 ((progress.getTotal() == Progress.INDETERMINATE) ||
570 (progress.getTotal() < transaction.getId())))
571 progress.setTotal(transaction.getId());
573 progress.setProgress(++processedTransactionCount);
574 publishProgress(progress);
578 profile.deleteNotPresentTransactions(db);
580 db.setTransactionSuccessful();
581 profile.setLastUpdateStamp();
591 @SuppressLint("DefaultLocale")
593 protected String doInBackground(Void... params) {
594 MobileLedgerProfile profile = Data.profile.get();
595 Data.backgroundTaskStarted();
597 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
598 return retrieveTransactionListLegacy(profile);
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) {