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.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;
74 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
75 private Pattern reAccountValue = Pattern.compile(
76 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
77 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
78 this.contextRef = contextRef;
80 private static void L(String msg) {
81 //debug("transaction-parser", msg);
84 protected void onProgressUpdate(Progress... values) {
85 super.onProgressUpdate(values);
86 MainActivity context = getContext();
87 if (context == null) return;
88 context.onRetrieveProgress(values[0]);
91 protected void onPreExecute() {
93 MainActivity context = getContext();
94 if (context == null) return;
95 context.onRetrieveStart();
98 protected void onPostExecute(String error) {
99 super.onPostExecute(error);
100 MainActivity context = getContext();
101 if (context == null) return;
102 context.onRetrieveDone(error);
105 protected void onCancelled() {
107 MainActivity context = getContext();
108 if (context == null) return;
109 context.onRetrieveDone(null);
111 private String retrieveTransactionListLegacy(MobileLedgerProfile profile)
112 throws IOException, ParseException, HTTPException {
113 Progress progress = new Progress();
114 int maxTransactionId = Progress.INDETERMINATE;
115 ArrayList<LedgerAccount> accountList = new ArrayList<>();
116 HashMap<String, Void> accountNames = new HashMap<>();
117 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
118 LedgerAccount lastAccount = null, prevAccount = null;
119 boolean onlyStarred = Data.optShowOnlyStarred.get();
121 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
122 http.setAllowUserInteraction(false);
123 publishProgress(progress);
124 switch (http.getResponseCode()) {
128 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
130 try (SQLiteDatabase db = MLDB.getDatabase()) {
131 try (InputStream resp = http.getInputStream()) {
132 if (http.getResponseCode() != 200)
133 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
134 db.beginTransaction();
136 prepareDbForRetrieval(db, profile);
138 int matchedTransactionsCount = 0;
141 ParserState state = ParserState.EXPECTING_ACCOUNT;
144 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
146 int processedTransactionCount = 0;
147 int transactionId = 0;
148 LedgerTransaction transaction = null;
150 while ((line = buf.readLine()) != null) {
153 m = reComment.matcher(line);
155 // TODO: comments are ignored for now
156 Log.v("transaction-parser", "Ignoring comment");
159 //L(String.format("State is %d", updating));
161 case EXPECTING_ACCOUNT:
162 if (line.equals("<h2>General Journal</h2>")) {
163 state = ParserState.EXPECTING_TRANSACTION;
164 L("→ expecting transaction");
165 // commit the current transaction and start a new one
166 // the account list in the UI should reflect the (committed)
167 // state of the database
168 db.setTransactionSuccessful();
170 Data.accounts.setList(accountList);
171 db.beginTransaction();
174 m = reAccountName.matcher(line);
176 String acct_encoded = m.group(1);
177 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
178 acct_name = acct_name.replace("\"", "");
179 L(String.format("found account: %s", acct_name));
181 prevAccount = lastAccount;
182 lastAccount = profile.tryLoadAccount(db, acct_name);
183 if (lastAccount == null)
184 lastAccount = new LedgerAccount(acct_name);
185 else lastAccount.removeAmounts();
186 profile.storeAccount(db, lastAccount);
188 if (prevAccount != null) prevAccount
189 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
190 // make sure the parent account(s) are present,
191 // synthesising them if necessary
192 // this happens when the (missing-in-HTML) parent account has
193 // only one child so we create a synthetic parent account record,
194 // copying the amounts when child's amounts are parsed
195 String parentName = lastAccount.getParentName();
196 if (parentName != null) {
197 Stack<String> toAppend = new Stack<>();
198 while (parentName != null) {
199 if (accountNames.containsKey(parentName)) break;
200 toAppend.push(parentName);
202 new LedgerAccount(parentName).getParentName();
204 syntheticAccounts.clear();
205 while (!toAppend.isEmpty()) {
206 String aName = toAppend.pop();
207 LedgerAccount acc = profile.tryLoadAccount(db, aName);
209 acc = new LedgerAccount(aName);
210 acc.setHiddenByStar(lastAccount.isHiddenByStar());
211 acc.setExpanded(!lastAccount.hasSubAccounts() ||
212 lastAccount.isExpanded());
214 acc.setHasSubAccounts(true);
215 acc.removeAmounts(); // filled below when amounts are parsed
216 if ((!onlyStarred || !acc.isHiddenByStar()) &&
217 acc.isVisible(accountList)) accountList.add(acc);
218 L(String.format("gap-filling with %s", aName));
219 accountNames.put(aName, null);
220 profile.storeAccount(db, acc);
221 syntheticAccounts.put(aName, acc);
225 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
226 lastAccount.isVisible(accountList))
227 accountList.add(lastAccount);
228 accountNames.put(acct_name, null);
230 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
231 L("→ expecting account amount");
235 case EXPECTING_ACCOUNT_AMOUNT:
236 m = reAccountValue.matcher(line);
237 boolean match_found = false;
242 String value = m.group(1);
243 String currency = m.group(2);
244 if (currency == null) currency = "";
245 value = value.replace(',', '.');
246 L("curr=" + currency + ", value=" + value);
247 final float val = Float.parseFloat(value);
248 profile.storeAccountValue(db, lastAccount.getName(), currency,
250 lastAccount.addAmount(val, currency);
251 for (LedgerAccount syn : syntheticAccounts.values()) {
252 syn.addAmount(val, currency);
253 profile.storeAccountValue(db, syn.getName(), currency, val);
258 state = ParserState.EXPECTING_ACCOUNT;
259 L("→ expecting account");
264 case EXPECTING_TRANSACTION:
265 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
266 m = reTransactionStart.matcher(line);
268 transactionId = Integer.valueOf(m.group(1));
269 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
270 L(String.format("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("transaction %d created for %s (%s) →" +
308 " expecting details", transactionId, date,
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("%d: %s = %s", transaction.getId(),
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(
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(
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) {