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 androidx.annotation.NonNull;
27 import net.ktnx.mobileledger.App;
28 import net.ktnx.mobileledger.err.HTTPException;
29 import net.ktnx.mobileledger.json.AccountListParser;
30 import net.ktnx.mobileledger.json.ParsedBalance;
31 import net.ktnx.mobileledger.json.ParsedLedgerAccount;
32 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
33 import net.ktnx.mobileledger.json.TransactionListParser;
34 import net.ktnx.mobileledger.model.Data;
35 import net.ktnx.mobileledger.model.LedgerAccount;
36 import net.ktnx.mobileledger.model.LedgerTransaction;
37 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
38 import net.ktnx.mobileledger.model.MobileLedgerProfile;
39 import net.ktnx.mobileledger.ui.activity.MainActivity;
40 import net.ktnx.mobileledger.utils.NetworkUtil;
42 import java.io.BufferedReader;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.InputStreamReader;
46 import java.lang.ref.WeakReference;
47 import java.net.HttpURLConnection;
48 import java.net.MalformedURLException;
49 import java.net.URLDecoder;
50 import java.nio.charset.StandardCharsets;
51 import java.text.ParseException;
52 import java.util.ArrayList;
53 import java.util.HashMap;
54 import java.util.Locale;
55 import java.util.Stack;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
59 import static net.ktnx.mobileledger.utils.Logger.debug;
62 public class RetrieveTransactionsTask
63 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
64 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
65 private static final Pattern reComment = Pattern.compile("^\\s*;");
66 private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
67 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
68 private static final Pattern reTransactionDescription =
69 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
70 private static final Pattern reTransactionDetails =
71 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
72 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
73 private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
74 private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
75 private WeakReference<MainActivity> contextRef;
77 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
78 private Pattern reAccountValue = Pattern.compile(
79 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
80 private MobileLedgerProfile profile;
81 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
82 @NonNull MobileLedgerProfile profile) {
83 this.contextRef = contextRef;
84 this.profile = profile;
86 private static void L(String msg) {
87 //debug("transaction-parser", msg);
90 protected void onProgressUpdate(Progress... values) {
91 super.onProgressUpdate(values);
92 MainActivity context = getContext();
93 if (context == null) return;
94 context.onRetrieveProgress(values[0]);
97 protected void onPreExecute() {
99 MainActivity context = getContext();
100 if (context == null) return;
101 context.onRetrieveStart();
104 protected void onPostExecute(String error) {
105 super.onPostExecute(error);
106 MainActivity context = getContext();
107 if (context == null) return;
108 context.onRetrieveDone(error);
111 protected void onCancelled() {
113 MainActivity context = getContext();
114 if (context == null) return;
115 context.onRetrieveDone(null);
117 private String retrieveTransactionListLegacy()
118 throws IOException, ParseException, HTTPException {
119 Progress progress = new Progress();
120 int maxTransactionId = Progress.INDETERMINATE;
121 ArrayList<LedgerAccount> accountList = new ArrayList<>();
122 HashMap<String, Void> accountNames = new HashMap<>();
123 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
124 LedgerAccount lastAccount = null, prevAccount = null;
125 boolean onlyStarred = Data.optShowOnlyStarred.get();
127 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
128 http.setAllowUserInteraction(false);
129 publishProgress(progress);
130 switch (http.getResponseCode()) {
134 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
137 SQLiteDatabase db = App.getDatabase();
138 try (InputStream resp = http.getInputStream()) {
139 if (http.getResponseCode() != 200)
140 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
141 db.beginTransaction();
143 prepareDbForRetrieval(db, profile);
145 int matchedTransactionsCount = 0;
148 ParserState state = ParserState.EXPECTING_ACCOUNT;
151 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
153 int processedTransactionCount = 0;
154 int transactionId = 0;
155 LedgerTransaction transaction = null;
157 while ((line = buf.readLine()) != null) {
160 m = reComment.matcher(line);
162 // TODO: comments are ignored for now
163 // Log.v("transaction-parser", "Ignoring comment");
166 //L(String.format("State is %d", updating));
168 case EXPECTING_ACCOUNT:
169 if (line.equals("<h2>General Journal</h2>")) {
170 state = ParserState.EXPECTING_TRANSACTION;
171 L("→ expecting transaction");
172 // commit the current transaction and start a new one
173 // the account list in the UI should reflect the (committed)
174 // state of the database
175 db.setTransactionSuccessful();
177 Data.accounts.setList(accountList);
178 db.beginTransaction();
181 m = reAccountName.matcher(line);
183 String acct_encoded = m.group(1);
184 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
185 acct_name = acct_name.replace("\"", "");
186 L(String.format("found account: %s", acct_name));
188 prevAccount = lastAccount;
189 lastAccount = profile.tryLoadAccount(db, acct_name);
190 if (lastAccount == null) lastAccount = new LedgerAccount(acct_name);
191 else lastAccount.removeAmounts();
192 profile.storeAccount(db, lastAccount);
194 if (prevAccount != null) prevAccount
195 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
196 // make sure the parent account(s) are present,
197 // synthesising them if necessary
198 // this happens when the (missing-in-HTML) parent account has
199 // only one child so we create a synthetic parent account record,
200 // copying the amounts when child's amounts are parsed
201 String parentName = lastAccount.getParentName();
202 if (parentName != null) {
203 Stack<String> toAppend = new Stack<>();
204 while (parentName != null) {
205 if (accountNames.containsKey(parentName)) break;
206 toAppend.push(parentName);
207 parentName = new LedgerAccount(parentName).getParentName();
209 syntheticAccounts.clear();
210 while (!toAppend.isEmpty()) {
211 String aName = toAppend.pop();
212 LedgerAccount acc = profile.tryLoadAccount(db, aName);
214 acc = new LedgerAccount(aName);
215 acc.setHiddenByStar(lastAccount.isHiddenByStar());
216 acc.setExpanded(!lastAccount.hasSubAccounts() ||
217 lastAccount.isExpanded());
219 acc.setHasSubAccounts(true);
220 acc.removeAmounts(); // filled below when amounts are parsed
221 if ((!onlyStarred || !acc.isHiddenByStar()) &&
222 acc.isVisible(accountList)) accountList.add(acc);
223 L(String.format("gap-filling with %s", aName));
224 accountNames.put(aName, null);
225 profile.storeAccount(db, acc);
226 syntheticAccounts.put(aName, acc);
230 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
231 lastAccount.isVisible(accountList))
232 accountList.add(lastAccount);
233 accountNames.put(acct_name, null);
235 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
236 L("→ expecting account amount");
240 case EXPECTING_ACCOUNT_AMOUNT:
241 m = reAccountValue.matcher(line);
242 boolean match_found = false;
247 String value = m.group(1);
248 String currency = m.group(2);
249 if (currency == null) currency = "";
252 Matcher tmpM = reDecimalComma.matcher(value);
254 value = value.replace(".", "");
255 value = value.replace(',', '.');
258 tmpM = reDecimalPoint.matcher(value);
260 value = value.replace(",", "");
261 value = value.replace(" ", "");
264 L("curr=" + currency + ", value=" + value);
265 final float val = Float.parseFloat(value);
266 profile.storeAccountValue(db, lastAccount.getName(), currency, val);
267 lastAccount.addAmount(val, currency);
268 for (LedgerAccount syn : syntheticAccounts.values()) {
269 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
270 currency, val, syn.getName()));
271 syn.addAmount(val, currency);
272 profile.storeAccountValue(db, syn.getName(), currency, val);
277 syntheticAccounts.clear();
278 state = ParserState.EXPECTING_ACCOUNT;
279 L("→ expecting account");
284 case EXPECTING_TRANSACTION:
285 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
286 m = reTransactionStart.matcher(line);
288 transactionId = Integer.valueOf(m.group(1));
289 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
290 L(String.format(Locale.ENGLISH,
291 "found transaction %d → expecting description",
293 progress.setProgress(++processedTransactionCount);
294 if (maxTransactionId < transactionId)
295 maxTransactionId = transactionId;
296 if ((progress.getTotal() == Progress.INDETERMINATE) ||
297 (progress.getTotal() < transactionId))
298 progress.setTotal(transactionId);
299 publishProgress(progress);
301 m = reEnd.matcher(line);
303 L("--- transaction value complete ---");
308 case EXPECTING_TRANSACTION_DESCRIPTION:
309 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
310 m = reTransactionDescription.matcher(line);
312 if (transactionId == 0) throw new TransactionParserException(
313 "Transaction Id is 0 while expecting " + "description");
315 String date = m.group(1);
317 int equalsIndex = date.indexOf('=');
318 if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
320 new LedgerTransaction(transactionId, date, m.group(2));
322 catch (ParseException e) {
324 return String.format("Error parsing date '%s'", date);
326 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
327 L(String.format(Locale.ENGLISH,
328 "transaction %d created for %s (%s) →" +
329 " expecting details", transactionId, date, m.group(2)));
333 case EXPECTING_TRANSACTION_DETAILS:
334 if (line.isEmpty()) {
335 // transaction data collected
336 if (transaction.existsInDb(db)) {
337 profile.markTransactionAsPresent(db, transaction);
338 matchedTransactionsCount++;
340 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
341 profile.markTransactionsBeforeTransactionAsPresent(db,
343 progress.setTotal(progress.getProgress());
344 publishProgress(progress);
349 profile.storeTransaction(db, transaction);
350 matchedTransactionsCount = 0;
351 progress.setTotal(maxTransactionId);
354 state = ParserState.EXPECTING_TRANSACTION;
355 L(String.format("transaction %s saved → expecting transaction",
356 transaction.getId()));
357 transaction.finishLoading();
359 // sounds like a good idea, but transaction-1 may not be the first one chronologically
360 // for example, when you add the initial seeding transaction after entering some others
361 // if (transactionId == 1) {
362 // L("This was the initial transaction. Terminating " +
368 m = reTransactionDetails.matcher(line);
370 String acc_name = m.group(1);
371 String amount = m.group(2);
372 String currency = m.group(3);
373 if (currency == null) currency = "";
374 amount = amount.replace(',', '.');
375 transaction.addAccount(new LedgerTransactionAccount(acc_name,
376 Float.valueOf(amount), currency));
377 L(String.format(Locale.ENGLISH, "%d: %s = %s",
378 transaction.getId(), acc_name, amount));
380 else throw new IllegalStateException(
381 String.format("Can't parse transaction %d " + "details: %s",
382 transactionId, line));
386 throw new RuntimeException(
387 String.format("Unknown parser updating %s", state.name()));
393 profile.deleteNotPresentTransactions(db);
394 db.setTransactionSuccessful();
396 profile.setLastUpdateStamp();
405 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
406 db.execSQL("UPDATE transactions set keep=0 where profile=?",
407 new String[]{profile.getUuid()});
408 db.execSQL("update account_values set keep=0 where profile=?;",
409 new String[]{profile.getUuid()});
410 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
412 private boolean retrieveAccountList() throws IOException, HTTPException {
413 Progress progress = new Progress();
415 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
416 http.setAllowUserInteraction(false);
417 switch (http.getResponseCode()) {
423 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
425 publishProgress(progress);
426 SQLiteDatabase db = App.getDatabase();
427 ArrayList<LedgerAccount> accountList = new ArrayList<>();
428 boolean listFilledOK = false;
429 try (InputStream resp = http.getInputStream()) {
430 if (http.getResponseCode() != 200)
431 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
433 db.beginTransaction();
435 profile.markAccountsAsNotPresent(db);
437 AccountListParser parser = new AccountListParser(resp);
439 LedgerAccount prevAccount = null;
443 ParsedLedgerAccount parsedAccount = parser.nextAccount();
444 if (parsedAccount == null) break;
446 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
447 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
448 else acc.removeAmounts();
450 profile.storeAccount(db, acc);
451 String lastCurrency = null;
452 float lastCurrencyAmount = 0;
453 for (ParsedBalance b : parsedAccount.getAibalance()) {
454 final String currency = b.getAcommodity();
455 final float amount = b.getAquantity().asFloat();
456 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
458 if (lastCurrency != null) {
459 profile.storeAccountValue(db, acc.getName(), lastCurrency,
461 acc.addAmount(lastCurrencyAmount, lastCurrency);
463 lastCurrency = currency;
464 lastCurrencyAmount = amount;
467 if (lastCurrency != null) {
468 profile.storeAccountValue(db, acc.getName(), lastCurrency,
470 acc.addAmount(lastCurrencyAmount, lastCurrency);
473 if (acc.isVisible(accountList)) accountList.add(acc);
475 if (prevAccount != null) {
476 prevAccount.setHasSubAccounts(
477 acc.getName().startsWith(prevAccount.getName() + ":"));
484 profile.deleteNotPresentAccounts(db);
486 db.setTransactionSuccessful();
493 // should not be set in the DB transaction, because of a possible deadlock
494 // with the main and DbOpQueueRunner threads
495 if (listFilledOK) Data.accounts.setList(accountList);
499 private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
500 Progress progress = new Progress();
501 int maxTransactionId = Progress.INDETERMINATE;
503 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
504 http.setAllowUserInteraction(false);
505 publishProgress(progress);
506 switch (http.getResponseCode()) {
512 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
514 SQLiteDatabase db = App.getDatabase();
515 try (InputStream resp = http.getInputStream()) {
516 if (http.getResponseCode() != 200)
517 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
519 db.beginTransaction();
521 profile.markTransactionsAsNotPresent(db);
523 int matchedTransactionsCount = 0;
524 TransactionListParser parser = new TransactionListParser(resp);
526 int processedTransactionCount = 0;
528 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
529 int orderAccumulator = 0;
530 int lastTransactionId = 0;
534 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
536 if (parsedTransaction == null) break;
538 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
539 if (transaction.getId() > lastTransactionId) orderAccumulator++;
540 else orderAccumulator--;
541 lastTransactionId = transaction.getId();
542 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
543 if (orderAccumulator > 30) {
544 transactionOrder = DetectedTransactionOrder.FILE;
545 debug("rtt", String.format(Locale.ENGLISH,
546 "Detected native file order after %d transactions (factor %d)",
547 processedTransactionCount, orderAccumulator));
548 progress.setTotal(Data.transactions.size());
550 else if (orderAccumulator < -30) {
551 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
552 debug("rtt", String.format(Locale.ENGLISH,
553 "Detected reverse chronological order after %d transactions (factor %d)",
554 processedTransactionCount, orderAccumulator));
558 if (transaction.existsInDb(db)) {
559 profile.markTransactionAsPresent(db, transaction);
560 matchedTransactionsCount++;
562 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
563 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
565 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
566 progress.setTotal(progress.getProgress());
567 publishProgress(progress);
568 db.setTransactionSuccessful();
569 profile.setLastUpdateStamp();
574 profile.storeTransaction(db, transaction);
575 matchedTransactionsCount = 0;
576 progress.setTotal(maxTransactionId);
580 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
581 ((progress.getTotal() == Progress.INDETERMINATE) ||
582 (progress.getTotal() < transaction.getId())))
583 progress.setTotal(transaction.getId());
585 progress.setProgress(++processedTransactionCount);
586 publishProgress(progress);
590 profile.deleteNotPresentTransactions(db);
592 db.setTransactionSuccessful();
593 profile.setLastUpdateStamp();
603 @SuppressLint("DefaultLocale")
605 protected String doInBackground(Void... params) {
606 Data.backgroundTaskStarted();
608 if (!retrieveAccountList() || !retrieveTransactionList())
609 return retrieveTransactionListLegacy();
612 catch (MalformedURLException e) {
614 return "Invalid server URL";
616 catch (HTTPException e) {
618 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
620 catch (IOException e) {
622 return e.getLocalizedMessage();
624 catch (ParseException e) {
626 return "Network error";
628 catch (OperationCanceledException e) {
630 return "Operation cancelled";
633 Data.backgroundTaskFinished();
636 private MainActivity getContext() {
637 return contextRef.get();
639 private void throwIfCancelled() {
640 if (isCancelled()) throw new OperationCanceledException(null);
642 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
644 private enum ParserState {
645 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
646 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
649 public class Progress {
650 public static final int INDETERMINATE = -1;
651 private int progress;
654 this(INDETERMINATE, INDETERMINATE);
656 Progress(int progress, int total) {
657 this.progress = progress;
660 public int getProgress() {
663 protected void setProgress(int progress) {
664 this.progress = progress;
666 public int getTotal() {
669 protected void setTotal(int total) {
674 private class TransactionParserException extends IllegalStateException {
675 TransactionParserException(String message) {