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;
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(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)
299 date = date.substring(equalsIndex + 1);
300 transaction = new LedgerTransaction(transactionId, date,
303 catch (ParseException e) {
305 return String.format("Error parsing date '%s'", date);
307 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
308 L(String.format(Locale.ENGLISH,
309 "transaction %d created for %s (%s) →" +
310 " expecting details", transactionId, date, m.group(2)));
314 case EXPECTING_TRANSACTION_DETAILS:
315 if (line.isEmpty()) {
316 // transaction data collected
317 if (transaction.existsInDb(db)) {
318 profile.markTransactionAsPresent(db, transaction);
319 matchedTransactionsCount++;
321 if (matchedTransactionsCount ==
322 MATCHING_TRANSACTIONS_LIMIT)
324 profile.markTransactionsBeforeTransactionAsPresent(db,
326 progress.setTotal(progress.getProgress());
327 publishProgress(progress);
332 profile.storeTransaction(db, transaction);
333 matchedTransactionsCount = 0;
334 progress.setTotal(maxTransactionId);
337 state = ParserState.EXPECTING_TRANSACTION;
338 L(String.format("transaction %s saved → expecting transaction",
339 transaction.getId()));
340 transaction.finishLoading();
342 // sounds like a good idea, but transaction-1 may not be the first one chronologically
343 // for example, when you add the initial seeding transaction after entering some others
344 // if (transactionId == 1) {
345 // L("This was the initial transaction. Terminating " +
351 m = reTransactionDetails.matcher(line);
353 String acc_name = m.group(1);
354 String amount = m.group(2);
355 String currency = m.group(3);
356 if (currency == null) currency = "";
357 amount = amount.replace(',', '.');
358 transaction.addAccount(
359 new LedgerTransactionAccount(acc_name,
360 Float.valueOf(amount), currency));
361 L(String.format(Locale.ENGLISH, "%d: %s = %s",
362 transaction.getId(), acc_name, amount));
364 else throw new IllegalStateException(String.format(
365 "Can't parse transaction %d " + "details: %s",
366 transactionId, line));
370 throw new RuntimeException(
371 String.format("Unknown parser updating %s", state.name()));
377 profile.deleteNotPresentTransactions(db);
378 db.setTransactionSuccessful();
380 profile.setLastUpdateStamp();
390 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
391 db.execSQL("UPDATE transactions set keep=0 where profile=?",
392 new String[]{profile.getUuid()});
393 db.execSQL("update account_values set keep=0 where profile=?;",
394 new String[]{profile.getUuid()});
395 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
397 private boolean retrieveAccountList(MobileLedgerProfile profile)
398 throws IOException, HTTPException {
399 Progress progress = new Progress();
401 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
402 http.setAllowUserInteraction(false);
403 switch (http.getResponseCode()) {
409 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
411 publishProgress(progress);
412 SQLiteDatabase db = MLDB.getDatabase();
413 ArrayList<LedgerAccount> accountList = new ArrayList<>();
414 boolean listFilledOK = false;
415 try (InputStream resp = http.getInputStream()) {
416 if (http.getResponseCode() != 200)
417 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
419 db.beginTransaction();
421 profile.markAccountsAsNotPresent(db);
423 AccountListParser parser = new AccountListParser(resp);
425 LedgerAccount prevAccount = null;
429 ParsedLedgerAccount parsedAccount = parser.nextAccount();
430 if (parsedAccount == null) break;
432 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
433 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
434 else acc.removeAmounts();
436 profile.storeAccount(db, acc);
437 String lastCurrency = null;
438 float lastCurrencyAmount = 0;
439 for (ParsedBalance b : parsedAccount.getAibalance()) {
440 final String currency = b.getAcommodity();
441 final float amount = b.getAquantity().asFloat();
442 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
444 if (lastCurrency != null) {
445 profile.storeAccountValue(db, acc.getName(), lastCurrency,
447 acc.addAmount(lastCurrencyAmount, lastCurrency);
449 lastCurrency = currency;
450 lastCurrencyAmount = amount;
453 if (lastCurrency != null) {
454 profile.storeAccountValue(db, acc.getName(), lastCurrency,
456 acc.addAmount(lastCurrencyAmount, lastCurrency);
459 if (acc.isVisible(accountList)) accountList.add(acc);
461 if (prevAccount != null) {
462 prevAccount.setHasSubAccounts(
463 acc.getName().startsWith(prevAccount.getName() + ":"));
470 profile.deleteNotPresentAccounts(db);
472 db.setTransactionSuccessful();
479 // should not be set in the DB transaction, because of a possible deadlock
480 // with the main and DbOpQueueRunner threads
481 if (listFilledOK) Data.accounts.setList(accountList);
485 private boolean retrieveTransactionList(MobileLedgerProfile profile)
486 throws IOException, ParseException, HTTPException {
487 Progress progress = new Progress();
488 int maxTransactionId = Progress.INDETERMINATE;
490 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
491 http.setAllowUserInteraction(false);
492 publishProgress(progress);
493 switch (http.getResponseCode()) {
499 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
501 SQLiteDatabase db = MLDB.getDatabase();
502 try (InputStream resp = http.getInputStream()) {
503 if (http.getResponseCode() != 200)
504 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
506 db.beginTransaction();
508 profile.markTransactionsAsNotPresent(db);
510 int matchedTransactionsCount = 0;
511 TransactionListParser parser = new TransactionListParser(resp);
513 int processedTransactionCount = 0;
515 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
516 int orderAccumulator = 0;
517 int lastTransactionId = 0;
521 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
523 if (parsedTransaction == null) break;
525 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
526 if (transaction.getId() > lastTransactionId) orderAccumulator++;
527 else orderAccumulator--;
528 lastTransactionId = transaction.getId();
529 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
530 if (orderAccumulator > 30) {
531 transactionOrder = DetectedTransactionOrder.FILE;
532 debug("rtt", String.format(Locale.ENGLISH,
533 "Detected native file order after %d transactions (factor %d)",
534 processedTransactionCount, orderAccumulator));
535 progress.setTotal(Data.transactions.size());
537 else if (orderAccumulator < -30) {
538 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
539 debug("rtt", String.format(Locale.ENGLISH,
540 "Detected reverse chronological order after %d transactions (factor %d)",
541 processedTransactionCount, orderAccumulator));
545 if (transaction.existsInDb(db)) {
546 profile.markTransactionAsPresent(db, transaction);
547 matchedTransactionsCount++;
549 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
550 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
552 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
553 progress.setTotal(progress.getProgress());
554 publishProgress(progress);
555 db.setTransactionSuccessful();
556 profile.setLastUpdateStamp();
561 profile.storeTransaction(db, transaction);
562 matchedTransactionsCount = 0;
563 progress.setTotal(maxTransactionId);
567 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
568 ((progress.getTotal() == Progress.INDETERMINATE) ||
569 (progress.getTotal() < transaction.getId())))
570 progress.setTotal(transaction.getId());
572 progress.setProgress(++processedTransactionCount);
573 publishProgress(progress);
577 profile.deleteNotPresentTransactions(db);
579 db.setTransactionSuccessful();
580 profile.setLastUpdateStamp();
590 @SuppressLint("DefaultLocale")
592 protected String doInBackground(Void... params) {
593 MobileLedgerProfile profile = Data.profile.get();
594 Data.backgroundTaskStarted();
596 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
597 return retrieveTransactionListLegacy(profile);
600 catch (MalformedURLException e) {
602 return "Invalid server URL";
604 catch (HTTPException e) {
606 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
608 catch (IOException e) {
610 return e.getLocalizedMessage();
612 catch (ParseException e) {
614 return "Network error";
616 catch (OperationCanceledException e) {
618 return "Operation cancelled";
621 Data.backgroundTaskFinished();
624 private MainActivity getContext() {
625 return contextRef.get();
627 private void throwIfCancelled() {
628 if (isCancelled()) throw new OperationCanceledException(null);
630 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
632 private enum ParserState {
633 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
634 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
637 public class Progress {
638 public static final int INDETERMINATE = -1;
639 private int progress;
642 this(INDETERMINATE, INDETERMINATE);
644 Progress(int progress, int total) {
645 this.progress = progress;
648 public int getProgress() {
651 protected void setProgress(int progress) {
652 this.progress = progress;
654 public int getTotal() {
657 protected void setTotal(int total) {
662 private class TransactionParserException extends IllegalStateException {
663 TransactionParserException(String message) {