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.App;
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.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());
133 SQLiteDatabase db = App.getDatabase();
134 try (InputStream resp = http.getInputStream()) {
135 if (http.getResponseCode() != 200)
136 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
137 db.beginTransaction();
139 prepareDbForRetrieval(db, profile);
141 int matchedTransactionsCount = 0;
144 ParserState state = ParserState.EXPECTING_ACCOUNT;
147 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
149 int processedTransactionCount = 0;
150 int transactionId = 0;
151 LedgerTransaction transaction = null;
153 while ((line = buf.readLine()) != null) {
156 m = reComment.matcher(line);
158 // TODO: comments are ignored for now
159 // Log.v("transaction-parser", "Ignoring comment");
162 //L(String.format("State is %d", updating));
164 case EXPECTING_ACCOUNT:
165 if (line.equals("<h2>General Journal</h2>")) {
166 state = ParserState.EXPECTING_TRANSACTION;
167 L("→ expecting transaction");
168 // commit the current transaction and start a new one
169 // the account list in the UI should reflect the (committed)
170 // state of the database
171 db.setTransactionSuccessful();
173 Data.accounts.setList(accountList);
174 db.beginTransaction();
177 m = reAccountName.matcher(line);
179 String acct_encoded = m.group(1);
180 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
181 acct_name = acct_name.replace("\"", "");
182 L(String.format("found account: %s", acct_name));
184 prevAccount = lastAccount;
185 lastAccount = profile.tryLoadAccount(db, acct_name);
186 if (lastAccount == null) 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);
203 parentName = 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, val);
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(Locale.ENGLISH,
271 "found transaction %d → expecting description",
273 progress.setProgress(++processedTransactionCount);
274 if (maxTransactionId < transactionId)
275 maxTransactionId = transactionId;
276 if ((progress.getTotal() == Progress.INDETERMINATE) ||
277 (progress.getTotal() < transactionId))
278 progress.setTotal(transactionId);
279 publishProgress(progress);
281 m = reEnd.matcher(line);
283 L("--- transaction value complete ---");
288 case EXPECTING_TRANSACTION_DESCRIPTION:
289 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
290 m = reTransactionDescription.matcher(line);
292 if (transactionId == 0) throw new TransactionParserException(
293 "Transaction Id is 0 while expecting " + "description");
295 String date = m.group(1);
297 int equalsIndex = date.indexOf('=');
298 if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
300 new LedgerTransaction(transactionId, date, m.group(2));
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 == MATCHING_TRANSACTIONS_LIMIT) {
321 profile.markTransactionsBeforeTransactionAsPresent(db,
323 progress.setTotal(progress.getProgress());
324 publishProgress(progress);
329 profile.storeTransaction(db, transaction);
330 matchedTransactionsCount = 0;
331 progress.setTotal(maxTransactionId);
334 state = ParserState.EXPECTING_TRANSACTION;
335 L(String.format("transaction %s saved → expecting transaction",
336 transaction.getId()));
337 transaction.finishLoading();
339 // sounds like a good idea, but transaction-1 may not be the first one chronologically
340 // for example, when you add the initial seeding transaction after entering some others
341 // if (transactionId == 1) {
342 // L("This was the initial transaction. Terminating " +
348 m = reTransactionDetails.matcher(line);
350 String acc_name = m.group(1);
351 String amount = m.group(2);
352 String currency = m.group(3);
353 if (currency == null) currency = "";
354 amount = amount.replace(',', '.');
355 transaction.addAccount(new LedgerTransactionAccount(acc_name,
356 Float.valueOf(amount), currency));
357 L(String.format(Locale.ENGLISH, "%d: %s = %s",
358 transaction.getId(), acc_name, amount));
360 else throw new IllegalStateException(
361 String.format("Can't parse transaction %d " + "details: %s",
362 transactionId, line));
366 throw new RuntimeException(
367 String.format("Unknown parser updating %s", state.name()));
373 profile.deleteNotPresentTransactions(db);
374 db.setTransactionSuccessful();
376 profile.setLastUpdateStamp();
385 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
386 db.execSQL("UPDATE transactions set keep=0 where profile=?",
387 new String[]{profile.getUuid()});
388 db.execSQL("update account_values set keep=0 where profile=?;",
389 new String[]{profile.getUuid()});
390 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
392 private boolean retrieveAccountList()
393 throws IOException, HTTPException {
394 Progress progress = new Progress();
396 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
397 http.setAllowUserInteraction(false);
398 switch (http.getResponseCode()) {
404 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
406 publishProgress(progress);
407 SQLiteDatabase db = App.getDatabase();
408 ArrayList<LedgerAccount> accountList = new ArrayList<>();
409 boolean listFilledOK = false;
410 try (InputStream resp = http.getInputStream()) {
411 if (http.getResponseCode() != 200)
412 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
414 db.beginTransaction();
416 profile.markAccountsAsNotPresent(db);
418 AccountListParser parser = new AccountListParser(resp);
420 LedgerAccount prevAccount = null;
424 ParsedLedgerAccount parsedAccount = parser.nextAccount();
425 if (parsedAccount == null) break;
427 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
428 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
429 else acc.removeAmounts();
431 profile.storeAccount(db, acc);
432 String lastCurrency = null;
433 float lastCurrencyAmount = 0;
434 for (ParsedBalance b : parsedAccount.getAibalance()) {
435 final String currency = b.getAcommodity();
436 final float amount = b.getAquantity().asFloat();
437 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
439 if (lastCurrency != null) {
440 profile.storeAccountValue(db, acc.getName(), lastCurrency,
442 acc.addAmount(lastCurrencyAmount, lastCurrency);
444 lastCurrency = currency;
445 lastCurrencyAmount = amount;
448 if (lastCurrency != null) {
449 profile.storeAccountValue(db, acc.getName(), lastCurrency,
451 acc.addAmount(lastCurrencyAmount, lastCurrency);
454 if (acc.isVisible(accountList)) accountList.add(acc);
456 if (prevAccount != null) {
457 prevAccount.setHasSubAccounts(
458 acc.getName().startsWith(prevAccount.getName() + ":"));
465 profile.deleteNotPresentAccounts(db);
467 db.setTransactionSuccessful();
474 // should not be set in the DB transaction, because of a possible deadlock
475 // with the main and DbOpQueueRunner threads
476 if (listFilledOK) Data.accounts.setList(accountList);
480 private boolean retrieveTransactionList()
481 throws IOException, ParseException, HTTPException {
482 Progress progress = new Progress();
483 int maxTransactionId = Progress.INDETERMINATE;
485 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
486 http.setAllowUserInteraction(false);
487 publishProgress(progress);
488 switch (http.getResponseCode()) {
494 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
496 SQLiteDatabase db = App.getDatabase();
497 try (InputStream resp = http.getInputStream()) {
498 if (http.getResponseCode() != 200)
499 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
501 db.beginTransaction();
503 profile.markTransactionsAsNotPresent(db);
505 int matchedTransactionsCount = 0;
506 TransactionListParser parser = new TransactionListParser(resp);
508 int processedTransactionCount = 0;
510 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
511 int orderAccumulator = 0;
512 int lastTransactionId = 0;
516 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
518 if (parsedTransaction == null) break;
520 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
521 if (transaction.getId() > lastTransactionId) orderAccumulator++;
522 else orderAccumulator--;
523 lastTransactionId = transaction.getId();
524 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
525 if (orderAccumulator > 30) {
526 transactionOrder = DetectedTransactionOrder.FILE;
527 debug("rtt", String.format(Locale.ENGLISH,
528 "Detected native file order after %d transactions (factor %d)",
529 processedTransactionCount, orderAccumulator));
530 progress.setTotal(Data.transactions.size());
532 else if (orderAccumulator < -30) {
533 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
534 debug("rtt", String.format(Locale.ENGLISH,
535 "Detected reverse chronological order after %d transactions (factor %d)",
536 processedTransactionCount, orderAccumulator));
540 if (transaction.existsInDb(db)) {
541 profile.markTransactionAsPresent(db, transaction);
542 matchedTransactionsCount++;
544 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
545 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
547 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
548 progress.setTotal(progress.getProgress());
549 publishProgress(progress);
550 db.setTransactionSuccessful();
551 profile.setLastUpdateStamp();
556 profile.storeTransaction(db, transaction);
557 matchedTransactionsCount = 0;
558 progress.setTotal(maxTransactionId);
562 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
563 ((progress.getTotal() == Progress.INDETERMINATE) ||
564 (progress.getTotal() < transaction.getId())))
565 progress.setTotal(transaction.getId());
567 progress.setProgress(++processedTransactionCount);
568 publishProgress(progress);
572 profile.deleteNotPresentTransactions(db);
574 db.setTransactionSuccessful();
575 profile.setLastUpdateStamp();
585 @SuppressLint("DefaultLocale")
587 protected String doInBackground(Void... params) {
588 Data.backgroundTaskStarted();
590 if (!retrieveAccountList() || !retrieveTransactionList())
591 return retrieveTransactionListLegacy();
594 catch (MalformedURLException e) {
596 return "Invalid server URL";
598 catch (HTTPException e) {
600 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
602 catch (IOException e) {
604 return e.getLocalizedMessage();
606 catch (ParseException e) {
608 return "Network error";
610 catch (OperationCanceledException e) {
612 return "Operation cancelled";
615 Data.backgroundTaskFinished();
618 private MainActivity getContext() {
619 return contextRef.get();
621 private void throwIfCancelled() {
622 if (isCancelled()) throw new OperationCanceledException(null);
624 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
626 private enum ParserState {
627 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
628 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
631 public class Progress {
632 public static final int INDETERMINATE = -1;
633 private int progress;
636 this(INDETERMINATE, INDETERMINATE);
638 Progress(int progress, int total) {
639 this.progress = progress;
642 public int getProgress() {
645 protected void setProgress(int progress) {
646 this.progress = progress;
648 public int getTotal() {
651 protected void setTotal(int total) {
656 private class TransactionParserException extends IllegalStateException {
657 TransactionParserException(String message) {