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;
24 import android.util.Log;
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.MLDB;
39 import net.ktnx.mobileledger.utils.NetworkUtil;
41 import java.io.BufferedReader;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.InputStreamReader;
45 import java.lang.ref.WeakReference;
46 import java.net.HttpURLConnection;
47 import java.net.MalformedURLException;
48 import java.net.URLDecoder;
49 import java.nio.charset.StandardCharsets;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.HashMap;
53 import java.util.Stack;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
58 public class RetrieveTransactionsTask
59 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
60 private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
61 private static final Pattern reComment = Pattern.compile("^\\s*;");
62 private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
63 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
64 private static final Pattern reTransactionDescription =
65 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
66 private static final Pattern reTransactionDetails =
67 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
68 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
69 private WeakReference<MainActivity> contextRef;
72 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
73 private Pattern reAccountValue = Pattern.compile(
74 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
75 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
76 this.contextRef = contextRef;
78 private static void L(String msg) {
79 //Log.d("transaction-parser", msg);
82 protected void onProgressUpdate(Progress... values) {
83 super.onProgressUpdate(values);
84 MainActivity context = getContext();
85 if (context == null) return;
86 context.onRetrieveProgress(values[0]);
89 protected void onPreExecute() {
91 MainActivity context = getContext();
92 if (context == null) return;
93 context.onRetrieveStart();
96 protected void onPostExecute(String error) {
97 super.onPostExecute(error);
98 MainActivity context = getContext();
99 if (context == null) return;
100 context.onRetrieveDone(error);
103 protected void onCancelled() {
105 MainActivity context = getContext();
106 if (context == null) return;
107 context.onRetrieveDone(null);
109 private String retrieveTransactionListLegacy(MobileLedgerProfile profile)
110 throws IOException, ParseException, HTTPException {
111 Progress progress = new Progress();
112 int maxTransactionId = Progress.INDETERMINATE;
113 ArrayList<LedgerAccount> accountList = new ArrayList<>();
114 HashMap<String, Void> accountNames = new HashMap<>();
115 HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
116 LedgerAccount lastAccount = null, prevAccount = null;
117 boolean onlyStarred = Data.optShowOnlyStarred.get();
119 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
120 http.setAllowUserInteraction(false);
121 publishProgress(progress);
122 switch (http.getResponseCode()) {
126 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
128 try (SQLiteDatabase db = MLDB.getDatabase()) {
129 try (InputStream resp = http.getInputStream()) {
130 if (http.getResponseCode() != 200)
131 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
132 db.beginTransaction();
134 prepareDbForRetrieval(db, profile);
136 int matchedTransactionsCount = 0;
139 ParserState state = ParserState.EXPECTING_ACCOUNT;
142 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
144 int processedTransactionCount = 0;
145 int transactionId = 0;
146 LedgerTransaction transaction = null;
148 while ((line = buf.readLine()) != null) {
151 m = reComment.matcher(line);
153 // TODO: comments are ignored for now
154 Log.v("transaction-parser", "Ignoring comment");
157 //L(String.format("State is %d", updating));
159 case EXPECTING_ACCOUNT:
160 if (line.equals("<h2>General Journal</h2>")) {
161 state = ParserState.EXPECTING_TRANSACTION;
162 L("→ expecting transaction");
163 // commit the current transaction and start a new one
164 // the account list in the UI should reflect the (committed)
165 // state of the database
166 db.setTransactionSuccessful();
168 Data.accounts.setList(accountList);
169 db.beginTransaction();
172 m = reAccountName.matcher(line);
174 String acct_encoded = m.group(1);
175 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
176 acct_name = acct_name.replace("\"", "");
177 L(String.format("found account: %s", acct_name));
179 prevAccount = lastAccount;
180 lastAccount = profile.tryLoadAccount(db, acct_name);
181 if (lastAccount == null)
182 lastAccount = new LedgerAccount(acct_name);
183 else lastAccount.removeAmounts();
184 profile.storeAccount(db, lastAccount);
186 if (prevAccount != null) prevAccount
187 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
188 // make sure the parent account(s) are present,
189 // synthesising them if necessary
190 // this happens when the (missing-in-HTML) parent account has
191 // only one child so we create a synthetic parent account record,
192 // copying the amounts when child's amounts are parsed
193 String parentName = lastAccount.getParentName();
194 if (parentName != null) {
195 Stack<String> toAppend = new Stack<>();
196 while (parentName != null) {
197 if (accountNames.containsKey(parentName)) break;
198 toAppend.push(parentName);
200 new LedgerAccount(parentName).getParentName();
202 syntheticAccounts.clear();
203 while (!toAppend.isEmpty()) {
204 String aName = toAppend.pop();
205 LedgerAccount acc = profile.tryLoadAccount(db, aName);
207 acc = new LedgerAccount(aName);
208 acc.setHiddenByStar(lastAccount.isHiddenByStar());
209 acc.setExpanded(!lastAccount.hasSubAccounts() ||
210 lastAccount.isExpanded());
212 acc.setHasSubAccounts(true);
213 acc.removeAmounts(); // filled below when amounts are parsed
214 if ((!onlyStarred || !acc.isHiddenByStar()) &&
215 acc.isVisible(accountList)) accountList.add(acc);
216 L(String.format("gap-filling with %s", aName));
217 accountNames.put(aName, null);
218 profile.storeAccount(db, acc);
219 syntheticAccounts.put(aName, acc);
223 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
224 lastAccount.isVisible(accountList))
225 accountList.add(lastAccount);
226 accountNames.put(acct_name, null);
228 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
229 L("→ expecting account amount");
233 case EXPECTING_ACCOUNT_AMOUNT:
234 m = reAccountValue.matcher(line);
235 boolean match_found = false;
240 String value = m.group(1);
241 String currency = m.group(2);
242 if (currency == null) currency = "";
243 value = value.replace(',', '.');
244 L("curr=" + currency + ", value=" + value);
245 final float val = Float.parseFloat(value);
246 profile.storeAccountValue(db, lastAccount.getName(), currency,
248 lastAccount.addAmount(val, currency);
249 for (LedgerAccount syn : syntheticAccounts.values()) {
250 syn.addAmount(val, currency);
251 profile.storeAccountValue(db, syn.getName(), currency, val);
256 state = ParserState.EXPECTING_ACCOUNT;
257 L("→ expecting account");
262 case EXPECTING_TRANSACTION:
263 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
264 m = reTransactionStart.matcher(line);
266 transactionId = Integer.valueOf(m.group(1));
267 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
268 L(String.format("found transaction %d → expecting description",
270 progress.setProgress(++processedTransactionCount);
271 if (maxTransactionId < transactionId)
272 maxTransactionId = transactionId;
273 if ((progress.getTotal() == Progress.INDETERMINATE) ||
274 (progress.getTotal() < transactionId))
275 progress.setTotal(transactionId);
276 publishProgress(progress);
278 m = reEnd.matcher(line);
280 L("--- transaction value complete ---");
285 case EXPECTING_TRANSACTION_DESCRIPTION:
286 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
287 m = reTransactionDescription.matcher(line);
289 if (transactionId == 0) throw new TransactionParserException(
290 "Transaction Id is 0 while expecting " + "description");
292 String date = m.group(1);
294 int equalsIndex = date.indexOf('=');
295 if (equalsIndex >= 0)
296 date = date.substring(equalsIndex + 1);
297 transaction = new LedgerTransaction(transactionId, date,
300 catch (ParseException e) {
302 return String.format("Error parsing date '%s'", date);
304 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
305 L(String.format("transaction %d created for %s (%s) →" +
306 " expecting details", transactionId, date,
311 case EXPECTING_TRANSACTION_DETAILS:
312 if (line.isEmpty()) {
313 // transaction data collected
314 if (transaction.existsInDb(db)) {
315 profile.markTransactionAsPresent(db, transaction);
316 matchedTransactionsCount++;
318 if (matchedTransactionsCount ==
319 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(
356 new LedgerTransactionAccount(acc_name,
357 Float.valueOf(amount), currency));
358 L(String.format("%d: %s = %s", transaction.getId(),
361 else throw new IllegalStateException(String.format(
362 "Can't parse transaction %d " + "details: %s",
363 transactionId, line));
367 throw new RuntimeException(
368 String.format("Unknown parser updating %s", state.name()));
374 profile.deleteNotPresentTransactions(db);
375 db.setTransactionSuccessful();
377 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(MobileLedgerProfile profile)
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 = MLDB.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(MobileLedgerProfile profile)
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 = MLDB.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 Log.d("rtt", String.format(
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 Log.d("rtt", String.format(
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 MobileLedgerProfile profile = Data.profile.get();
591 Data.backgroundTaskCount.incrementAndGet();
593 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
594 return retrieveTransactionListLegacy(profile);
597 catch (MalformedURLException e) {
599 return "Invalid server URL";
601 catch (HTTPException e) {
603 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
605 catch (IOException e) {
607 return e.getLocalizedMessage();
609 catch (ParseException e) {
611 return "Network error";
613 catch (OperationCanceledException e) {
615 return "Operation cancelled";
618 Data.backgroundTaskCount.decrementAndGet();
621 private MainActivity getContext() {
622 return contextRef.get();
624 private void throwIfCancelled() {
625 if (isCancelled()) throw new OperationCanceledException(null);
627 enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
629 private enum ParserState {
630 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
631 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
634 public class Progress {
635 public static final int INDETERMINATE = -1;
636 private int progress;
639 this(INDETERMINATE, INDETERMINATE);
641 Progress(int progress, int total) {
642 this.progress = progress;
645 public int getProgress() {
648 protected void setProgress(int progress) {
649 this.progress = progress;
651 public int getTotal() {
654 protected void setTotal(int total) {
659 private class TransactionParserException extends IllegalStateException {
660 TransactionParserException(String message) {