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 androidx.annotation.NonNull;
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 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 private MobileLedgerProfile profile;
79 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
80 @NonNull MobileLedgerProfile profile) {
81 this.contextRef = contextRef;
82 this.profile = profile;
84 private static void L(String msg) {
85 //debug("transaction-parser", msg);
88 protected void onProgressUpdate(Progress... values) {
89 super.onProgressUpdate(values);
90 MainActivity context = getContext();
91 if (context == null) return;
92 context.onRetrieveProgress(values[0]);
95 protected void onPreExecute() {
97 MainActivity context = getContext();
98 if (context == null) return;
99 context.onRetrieveStart();
102 protected void onPostExecute(String error) {
103 super.onPostExecute(error);
104 MainActivity context = getContext();
105 if (context == null) return;
106 context.onRetrieveDone(error);
109 protected void onCancelled() {
111 MainActivity context = getContext();
112 if (context == null) return;
113 context.onRetrieveDone(null);
115 private String retrieveTransactionListLegacy()
116 throws IOException, ParseException, HTTPException {
117 Progress progress = new Progress();
118 int maxTransactionId = Progress.INDETERMINATE;
119 ArrayList<LedgerAccount> accountList = new ArrayList<>();
120 HashMap<String, Void> accountNames = new HashMap<>();
121 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
122 LedgerAccount lastAccount = null, prevAccount = null;
123 boolean onlyStarred = Data.optShowOnlyStarred.get();
125 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
126 http.setAllowUserInteraction(false);
127 publishProgress(progress);
128 switch (http.getResponseCode()) {
132 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
135 SQLiteDatabase db = App.getDatabase();
136 try (InputStream resp = http.getInputStream()) {
137 if (http.getResponseCode() != 200)
138 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
139 db.beginTransaction();
141 prepareDbForRetrieval(db, profile);
143 int matchedTransactionsCount = 0;
146 ParserState state = ParserState.EXPECTING_ACCOUNT;
149 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
151 int processedTransactionCount = 0;
152 int transactionId = 0;
153 LedgerTransaction transaction = null;
155 while ((line = buf.readLine()) != null) {
158 m = reComment.matcher(line);
160 // TODO: comments are ignored for now
161 // Log.v("transaction-parser", "Ignoring comment");
164 //L(String.format("State is %d", updating));
166 case EXPECTING_ACCOUNT:
167 if (line.equals("<h2>General Journal</h2>")) {
168 state = ParserState.EXPECTING_TRANSACTION;
169 L("→ expecting transaction");
170 // commit the current transaction and start a new one
171 // the account list in the UI should reflect the (committed)
172 // state of the database
173 db.setTransactionSuccessful();
175 Data.accounts.setList(accountList);
176 db.beginTransaction();
179 m = reAccountName.matcher(line);
181 String acct_encoded = m.group(1);
182 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
183 acct_name = acct_name.replace("\"", "");
184 L(String.format("found account: %s", acct_name));
186 prevAccount = lastAccount;
187 lastAccount = profile.tryLoadAccount(db, acct_name);
188 if (lastAccount == null) lastAccount = new LedgerAccount(acct_name);
189 else lastAccount.removeAmounts();
190 profile.storeAccount(db, lastAccount);
192 if (prevAccount != null) prevAccount
193 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
194 // make sure the parent account(s) are present,
195 // synthesising them if necessary
196 // this happens when the (missing-in-HTML) parent account has
197 // only one child so we create a synthetic parent account record,
198 // copying the amounts when child's amounts are parsed
199 String parentName = lastAccount.getParentName();
200 if (parentName != null) {
201 Stack<String> toAppend = new Stack<>();
202 while (parentName != null) {
203 if (accountNames.containsKey(parentName)) break;
204 toAppend.push(parentName);
205 parentName = new LedgerAccount(parentName).getParentName();
207 syntheticAccounts.clear();
208 while (!toAppend.isEmpty()) {
209 String aName = toAppend.pop();
210 LedgerAccount acc = profile.tryLoadAccount(db, aName);
212 acc = new LedgerAccount(aName);
213 acc.setHiddenByStar(lastAccount.isHiddenByStar());
214 acc.setExpanded(!lastAccount.hasSubAccounts() ||
215 lastAccount.isExpanded());
217 acc.setHasSubAccounts(true);
218 acc.removeAmounts(); // filled below when amounts are parsed
219 if ((!onlyStarred || !acc.isHiddenByStar()) &&
220 acc.isVisible(accountList)) accountList.add(acc);
221 L(String.format("gap-filling with %s", aName));
222 accountNames.put(aName, null);
223 profile.storeAccount(db, acc);
224 syntheticAccounts.put(aName, acc);
228 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
229 lastAccount.isVisible(accountList))
230 accountList.add(lastAccount);
231 accountNames.put(acct_name, null);
233 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
234 L("→ expecting account amount");
238 case EXPECTING_ACCOUNT_AMOUNT:
239 m = reAccountValue.matcher(line);
240 boolean match_found = false;
245 String value = m.group(1);
246 String currency = m.group(2);
247 if (currency == null) currency = "";
248 value = value.replace(',', '.');
249 L("curr=" + currency + ", value=" + value);
250 final float val = Float.parseFloat(value);
251 profile.storeAccountValue(db, lastAccount.getName(), currency, val);
252 lastAccount.addAmount(val, currency);
253 for (LedgerAccount syn : syntheticAccounts.values()) {
254 syn.addAmount(val, currency);
255 profile.storeAccountValue(db, syn.getName(), currency, val);
260 state = ParserState.EXPECTING_ACCOUNT;
261 L("→ expecting account");
266 case EXPECTING_TRANSACTION:
267 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
268 m = reTransactionStart.matcher(line);
270 transactionId = Integer.valueOf(m.group(1));
271 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
272 L(String.format(Locale.ENGLISH,
273 "found transaction %d → expecting description",
275 progress.setProgress(++processedTransactionCount);
276 if (maxTransactionId < transactionId)
277 maxTransactionId = transactionId;
278 if ((progress.getTotal() == Progress.INDETERMINATE) ||
279 (progress.getTotal() < transactionId))
280 progress.setTotal(transactionId);
281 publishProgress(progress);
283 m = reEnd.matcher(line);
285 L("--- transaction value complete ---");
290 case EXPECTING_TRANSACTION_DESCRIPTION:
291 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
292 m = reTransactionDescription.matcher(line);
294 if (transactionId == 0) throw new TransactionParserException(
295 "Transaction Id is 0 while expecting " + "description");
297 String date = m.group(1);
299 int equalsIndex = date.indexOf('=');
300 if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
302 new LedgerTransaction(transactionId, date, m.group(2));
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 == 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(new LedgerTransactionAccount(acc_name,
358 Float.valueOf(amount), currency));
359 L(String.format(Locale.ENGLISH, "%d: %s = %s",
360 transaction.getId(), acc_name, amount));
362 else throw new IllegalStateException(
363 String.format("Can't parse transaction %d " + "details: %s",
364 transactionId, line));
368 throw new RuntimeException(
369 String.format("Unknown parser updating %s", state.name()));
375 profile.deleteNotPresentTransactions(db);
376 db.setTransactionSuccessful();
378 profile.setLastUpdateStamp();
387 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
388 db.execSQL("UPDATE transactions set keep=0 where profile=?",
389 new String[]{profile.getUuid()});
390 db.execSQL("update account_values set keep=0 where profile=?;",
391 new String[]{profile.getUuid()});
392 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
394 private boolean retrieveAccountList()
395 throws IOException, HTTPException {
396 Progress progress = new Progress();
398 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
399 http.setAllowUserInteraction(false);
400 switch (http.getResponseCode()) {
406 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
408 publishProgress(progress);
409 SQLiteDatabase db = App.getDatabase();
410 ArrayList<LedgerAccount> accountList = new ArrayList<>();
411 boolean listFilledOK = false;
412 try (InputStream resp = http.getInputStream()) {
413 if (http.getResponseCode() != 200)
414 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
416 db.beginTransaction();
418 profile.markAccountsAsNotPresent(db);
420 AccountListParser parser = new AccountListParser(resp);
422 LedgerAccount prevAccount = null;
426 ParsedLedgerAccount parsedAccount = parser.nextAccount();
427 if (parsedAccount == null) break;
429 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
430 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
431 else acc.removeAmounts();
433 profile.storeAccount(db, acc);
434 String lastCurrency = null;
435 float lastCurrencyAmount = 0;
436 for (ParsedBalance b : parsedAccount.getAibalance()) {
437 final String currency = b.getAcommodity();
438 final float amount = b.getAquantity().asFloat();
439 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
441 if (lastCurrency != null) {
442 profile.storeAccountValue(db, acc.getName(), lastCurrency,
444 acc.addAmount(lastCurrencyAmount, lastCurrency);
446 lastCurrency = currency;
447 lastCurrencyAmount = amount;
450 if (lastCurrency != null) {
451 profile.storeAccountValue(db, acc.getName(), lastCurrency,
453 acc.addAmount(lastCurrencyAmount, lastCurrency);
456 if (acc.isVisible(accountList)) accountList.add(acc);
458 if (prevAccount != null) {
459 prevAccount.setHasSubAccounts(
460 acc.getName().startsWith(prevAccount.getName() + ":"));
467 profile.deleteNotPresentAccounts(db);
469 db.setTransactionSuccessful();
476 // should not be set in the DB transaction, because of a possible deadlock
477 // with the main and DbOpQueueRunner threads
478 if (listFilledOK) Data.accounts.setList(accountList);
482 private boolean retrieveTransactionList()
483 throws IOException, ParseException, HTTPException {
484 Progress progress = new Progress();
485 int maxTransactionId = Progress.INDETERMINATE;
487 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
488 http.setAllowUserInteraction(false);
489 publishProgress(progress);
490 switch (http.getResponseCode()) {
496 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
498 SQLiteDatabase db = App.getDatabase();
499 try (InputStream resp = http.getInputStream()) {
500 if (http.getResponseCode() != 200)
501 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
503 db.beginTransaction();
505 profile.markTransactionsAsNotPresent(db);
507 int matchedTransactionsCount = 0;
508 TransactionListParser parser = new TransactionListParser(resp);
510 int processedTransactionCount = 0;
512 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
513 int orderAccumulator = 0;
514 int lastTransactionId = 0;
518 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
520 if (parsedTransaction == null) break;
522 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
523 if (transaction.getId() > lastTransactionId) orderAccumulator++;
524 else orderAccumulator--;
525 lastTransactionId = transaction.getId();
526 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
527 if (orderAccumulator > 30) {
528 transactionOrder = DetectedTransactionOrder.FILE;
529 debug("rtt", String.format(Locale.ENGLISH,
530 "Detected native file order after %d transactions (factor %d)",
531 processedTransactionCount, orderAccumulator));
532 progress.setTotal(Data.transactions.size());
534 else if (orderAccumulator < -30) {
535 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
536 debug("rtt", String.format(Locale.ENGLISH,
537 "Detected reverse chronological order after %d transactions (factor %d)",
538 processedTransactionCount, orderAccumulator));
542 if (transaction.existsInDb(db)) {
543 profile.markTransactionAsPresent(db, transaction);
544 matchedTransactionsCount++;
546 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
547 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
549 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
550 progress.setTotal(progress.getProgress());
551 publishProgress(progress);
552 db.setTransactionSuccessful();
553 profile.setLastUpdateStamp();
558 profile.storeTransaction(db, transaction);
559 matchedTransactionsCount = 0;
560 progress.setTotal(maxTransactionId);
564 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
565 ((progress.getTotal() == Progress.INDETERMINATE) ||
566 (progress.getTotal() < transaction.getId())))
567 progress.setTotal(transaction.getId());
569 progress.setProgress(++processedTransactionCount);
570 publishProgress(progress);
574 profile.deleteNotPresentTransactions(db);
576 db.setTransactionSuccessful();
577 profile.setLastUpdateStamp();
587 @SuppressLint("DefaultLocale")
589 protected String doInBackground(Void... params) {
590 Data.backgroundTaskStarted();
592 if (!retrieveAccountList() || !retrieveTransactionList())
593 return retrieveTransactionListLegacy();
596 catch (MalformedURLException e) {
598 return "Invalid server URL";
600 catch (HTTPException e) {
602 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
604 catch (IOException e) {
606 return e.getLocalizedMessage();
608 catch (ParseException e) {
610 return "Network error";
612 catch (OperationCanceledException e) {
614 return "Operation cancelled";
617 Data.backgroundTaskFinished();
620 private MainActivity getContext() {
621 return contextRef.get();
623 private void throwIfCancelled() {
624 if (isCancelled()) throw new OperationCanceledException(null);
626 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
628 private enum ParserState {
629 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
630 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
633 public class Progress {
634 public static final int INDETERMINATE = -1;
635 private int progress;
638 this(INDETERMINATE, INDETERMINATE);
640 Progress(int progress, int total) {
641 this.progress = progress;
644 public int getProgress() {
647 protected void setProgress(int progress) {
648 this.progress = progress;
650 public int getTotal() {
653 protected void setTotal(int total) {
658 private class TransactionParserException extends IllegalStateException {
659 TransactionParserException(String message) {