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());
132 // FIXME: why the resource block here? that would close the global DB connection
133 try (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)
187 lastAccount = new LedgerAccount(acct_name);
188 else lastAccount.removeAmounts();
189 profile.storeAccount(db, lastAccount);
191 if (prevAccount != null) prevAccount
192 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
193 // make sure the parent account(s) are present,
194 // synthesising them if necessary
195 // this happens when the (missing-in-HTML) parent account has
196 // only one child so we create a synthetic parent account record,
197 // copying the amounts when child's amounts are parsed
198 String parentName = lastAccount.getParentName();
199 if (parentName != null) {
200 Stack<String> toAppend = new Stack<>();
201 while (parentName != null) {
202 if (accountNames.containsKey(parentName)) break;
203 toAppend.push(parentName);
205 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,
253 lastAccount.addAmount(val, currency);
254 for (LedgerAccount syn : syntheticAccounts.values()) {
255 syn.addAmount(val, currency);
256 profile.storeAccountValue(db, syn.getName(), currency,
262 state = ParserState.EXPECTING_ACCOUNT;
263 L("→ expecting account");
268 case EXPECTING_TRANSACTION:
269 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
270 m = reTransactionStart.matcher(line);
272 transactionId = Integer.valueOf(m.group(1));
273 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
274 L(String.format(Locale.ENGLISH,
275 "found transaction %d → expecting description",
277 progress.setProgress(++processedTransactionCount);
278 if (maxTransactionId < transactionId)
279 maxTransactionId = transactionId;
280 if ((progress.getTotal() == Progress.INDETERMINATE) ||
281 (progress.getTotal() < transactionId))
282 progress.setTotal(transactionId);
283 publishProgress(progress);
285 m = reEnd.matcher(line);
287 L("--- transaction value complete ---");
292 case EXPECTING_TRANSACTION_DESCRIPTION:
293 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
294 m = reTransactionDescription.matcher(line);
296 if (transactionId == 0) throw new TransactionParserException(
297 "Transaction Id is 0 while expecting " + "description");
299 String date = m.group(1);
301 int equalsIndex = date.indexOf('=');
302 if (equalsIndex >= 0)
303 date = date.substring(equalsIndex + 1);
304 transaction = new LedgerTransaction(transactionId, date,
307 catch (ParseException e) {
309 return String.format("Error parsing date '%s'", date);
311 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
312 L(String.format(Locale.ENGLISH,
313 "transaction %d created for %s (%s) →" +
314 " expecting details", transactionId, date, m.group(2)));
318 case EXPECTING_TRANSACTION_DETAILS:
319 if (line.isEmpty()) {
320 // transaction data collected
321 if (transaction.existsInDb(db)) {
322 profile.markTransactionAsPresent(db, transaction);
323 matchedTransactionsCount++;
325 if (matchedTransactionsCount ==
326 MATCHING_TRANSACTIONS_LIMIT)
328 profile.markTransactionsBeforeTransactionAsPresent(db,
330 progress.setTotal(progress.getProgress());
331 publishProgress(progress);
336 profile.storeTransaction(db, transaction);
337 matchedTransactionsCount = 0;
338 progress.setTotal(maxTransactionId);
341 state = ParserState.EXPECTING_TRANSACTION;
342 L(String.format("transaction %s saved → expecting transaction",
343 transaction.getId()));
344 transaction.finishLoading();
346 // sounds like a good idea, but transaction-1 may not be the first one chronologically
347 // for example, when you add the initial seeding transaction after entering some others
348 // if (transactionId == 1) {
349 // L("This was the initial transaction. Terminating " +
355 m = reTransactionDetails.matcher(line);
357 String acc_name = m.group(1);
358 String amount = m.group(2);
359 String currency = m.group(3);
360 if (currency == null) currency = "";
361 amount = amount.replace(',', '.');
362 transaction.addAccount(
363 new LedgerTransactionAccount(acc_name,
364 Float.valueOf(amount), currency));
365 L(String.format(Locale.ENGLISH, "%d: %s = %s",
366 transaction.getId(), acc_name, amount));
368 else throw new IllegalStateException(String.format(
369 "Can't parse transaction %d " + "details: %s",
370 transactionId, line));
374 throw new RuntimeException(
375 String.format("Unknown parser updating %s", state.name()));
381 profile.deleteNotPresentTransactions(db);
382 db.setTransactionSuccessful();
384 profile.setLastUpdateStamp();
394 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
395 db.execSQL("UPDATE transactions set keep=0 where profile=?",
396 new String[]{profile.getUuid()});
397 db.execSQL("update account_values set keep=0 where profile=?;",
398 new String[]{profile.getUuid()});
399 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
401 private boolean retrieveAccountList()
402 throws IOException, HTTPException {
403 Progress progress = new Progress();
405 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
406 http.setAllowUserInteraction(false);
407 switch (http.getResponseCode()) {
413 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
415 publishProgress(progress);
416 SQLiteDatabase db = App.getDatabase();
417 ArrayList<LedgerAccount> accountList = new ArrayList<>();
418 boolean listFilledOK = false;
419 try (InputStream resp = http.getInputStream()) {
420 if (http.getResponseCode() != 200)
421 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
423 db.beginTransaction();
425 profile.markAccountsAsNotPresent(db);
427 AccountListParser parser = new AccountListParser(resp);
429 LedgerAccount prevAccount = null;
433 ParsedLedgerAccount parsedAccount = parser.nextAccount();
434 if (parsedAccount == null) break;
436 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
437 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
438 else acc.removeAmounts();
440 profile.storeAccount(db, acc);
441 String lastCurrency = null;
442 float lastCurrencyAmount = 0;
443 for (ParsedBalance b : parsedAccount.getAibalance()) {
444 final String currency = b.getAcommodity();
445 final float amount = b.getAquantity().asFloat();
446 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
448 if (lastCurrency != null) {
449 profile.storeAccountValue(db, acc.getName(), lastCurrency,
451 acc.addAmount(lastCurrencyAmount, lastCurrency);
453 lastCurrency = currency;
454 lastCurrencyAmount = amount;
457 if (lastCurrency != null) {
458 profile.storeAccountValue(db, acc.getName(), lastCurrency,
460 acc.addAmount(lastCurrencyAmount, lastCurrency);
463 if (acc.isVisible(accountList)) accountList.add(acc);
465 if (prevAccount != null) {
466 prevAccount.setHasSubAccounts(
467 acc.getName().startsWith(prevAccount.getName() + ":"));
474 profile.deleteNotPresentAccounts(db);
476 db.setTransactionSuccessful();
483 // should not be set in the DB transaction, because of a possible deadlock
484 // with the main and DbOpQueueRunner threads
485 if (listFilledOK) Data.accounts.setList(accountList);
489 private boolean retrieveTransactionList()
490 throws IOException, ParseException, HTTPException {
491 Progress progress = new Progress();
492 int maxTransactionId = Progress.INDETERMINATE;
494 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
495 http.setAllowUserInteraction(false);
496 publishProgress(progress);
497 switch (http.getResponseCode()) {
503 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
505 SQLiteDatabase db = App.getDatabase();
506 try (InputStream resp = http.getInputStream()) {
507 if (http.getResponseCode() != 200)
508 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
510 db.beginTransaction();
512 profile.markTransactionsAsNotPresent(db);
514 int matchedTransactionsCount = 0;
515 TransactionListParser parser = new TransactionListParser(resp);
517 int processedTransactionCount = 0;
519 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
520 int orderAccumulator = 0;
521 int lastTransactionId = 0;
525 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
527 if (parsedTransaction == null) break;
529 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
530 if (transaction.getId() > lastTransactionId) orderAccumulator++;
531 else orderAccumulator--;
532 lastTransactionId = transaction.getId();
533 if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
534 if (orderAccumulator > 30) {
535 transactionOrder = DetectedTransactionOrder.FILE;
536 debug("rtt", String.format(Locale.ENGLISH,
537 "Detected native file order after %d transactions (factor %d)",
538 processedTransactionCount, orderAccumulator));
539 progress.setTotal(Data.transactions.size());
541 else if (orderAccumulator < -30) {
542 transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
543 debug("rtt", String.format(Locale.ENGLISH,
544 "Detected reverse chronological order after %d transactions (factor %d)",
545 processedTransactionCount, orderAccumulator));
549 if (transaction.existsInDb(db)) {
550 profile.markTransactionAsPresent(db, transaction);
551 matchedTransactionsCount++;
553 if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
554 (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
556 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
557 progress.setTotal(progress.getProgress());
558 publishProgress(progress);
559 db.setTransactionSuccessful();
560 profile.setLastUpdateStamp();
565 profile.storeTransaction(db, transaction);
566 matchedTransactionsCount = 0;
567 progress.setTotal(maxTransactionId);
571 if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
572 ((progress.getTotal() == Progress.INDETERMINATE) ||
573 (progress.getTotal() < transaction.getId())))
574 progress.setTotal(transaction.getId());
576 progress.setProgress(++processedTransactionCount);
577 publishProgress(progress);
581 profile.deleteNotPresentTransactions(db);
583 db.setTransactionSuccessful();
584 profile.setLastUpdateStamp();
594 @SuppressLint("DefaultLocale")
596 protected String doInBackground(Void... params) {
597 Data.backgroundTaskStarted();
599 if (!retrieveAccountList() || !retrieveTransactionList())
600 return retrieveTransactionListLegacy();
603 catch (MalformedURLException e) {
605 return "Invalid server URL";
607 catch (HTTPException e) {
609 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
611 catch (IOException e) {
613 return e.getLocalizedMessage();
615 catch (ParseException e) {
617 return "Network error";
619 catch (OperationCanceledException e) {
621 return "Operation cancelled";
624 Data.backgroundTaskFinished();
627 private MainActivity getContext() {
628 return contextRef.get();
630 private void throwIfCancelled() {
631 if (isCancelled()) throw new OperationCanceledException(null);
633 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
635 private enum ParserState {
636 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
637 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
640 public class Progress {
641 public static final int INDETERMINATE = -1;
642 private int progress;
645 this(INDETERMINATE, INDETERMINATE);
647 Progress(int progress, int total) {
648 this.progress = progress;
651 public int getProgress() {
654 protected void setProgress(int progress) {
655 this.progress = progress;
657 public int getTotal() {
660 protected void setTotal(int total) {
665 private class TransactionParserException extends IllegalStateException {
666 TransactionParserException(String message) {