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 = 50;
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 LedgerAccount lastAccount = null, prevAccount = null;
116 boolean onlyStarred = Data.optShowOnlyStarred.get();
118 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
119 http.setAllowUserInteraction(false);
120 publishProgress(progress);
121 switch (http.getResponseCode()) {
125 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
127 try (SQLiteDatabase db = MLDB.getDatabase()) {
128 try (InputStream resp = http.getInputStream()) {
129 if (http.getResponseCode() != 200)
130 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
131 db.beginTransaction();
133 prepareDbForRetrieval(db, profile);
135 int matchedTransactionsCount = 0;
138 ParserState state = ParserState.EXPECTING_ACCOUNT;
141 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
143 int processedTransactionCount = 0;
144 int transactionId = 0;
145 LedgerTransaction transaction = null;
147 while ((line = buf.readLine()) != null) {
150 m = reComment.matcher(line);
152 // TODO: comments are ignored for now
153 Log.v("transaction-parser", "Ignoring comment");
156 //L(String.format("State is %d", updating));
158 case EXPECTING_ACCOUNT:
159 if (line.equals("<h2>General Journal</h2>")) {
160 state = ParserState.EXPECTING_TRANSACTION;
161 L("→ expecting transaction");
162 // commit the current transaction and start a new one
163 // the account list in the UI should reflect the (committed)
164 // state of the database
165 db.setTransactionSuccessful();
167 Data.accounts.setList(accountList);
168 db.beginTransaction();
171 m = reAccountName.matcher(line);
173 String acct_encoded = m.group(1);
174 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
175 acct_name = acct_name.replace("\"", "");
176 L(String.format("found account: %s", acct_name));
178 prevAccount = lastAccount;
179 lastAccount = profile.tryLoadAccount(db, acct_name);
180 if (lastAccount == null)
181 lastAccount = new LedgerAccount(acct_name);
182 else lastAccount.removeAmounts();
183 profile.storeAccount(db, lastAccount);
185 if (prevAccount != null) prevAccount
186 .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
187 // make sure the parent account(s) are present,
188 // synthesising them if necessary
189 String parentName = lastAccount.getParentName();
190 if (parentName != null) {
191 Stack<String> toAppend = new Stack<>();
192 while (parentName != null) {
193 if (accountNames.containsKey(parentName)) break;
194 toAppend.push(parentName);
196 new LedgerAccount(parentName).getParentName();
198 while (!toAppend.isEmpty()) {
199 String aName = toAppend.pop();
200 LedgerAccount acc = new LedgerAccount(aName);
201 acc.setHiddenByStar(lastAccount.isHiddenByStar());
202 acc.setHasSubAccounts(true);
203 if ((!onlyStarred || !acc.isHiddenByStar()) &&
204 acc.isVisible(accountList)) accountList.add(acc);
205 L(String.format("gap-filling with %s", aName));
206 accountNames.put(aName, null);
207 profile.storeAccount(db, acc);
211 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
212 lastAccount.isVisible(accountList))
213 accountList.add(lastAccount);
214 accountNames.put(acct_name, null);
216 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
217 L("→ expecting account amount");
221 case EXPECTING_ACCOUNT_AMOUNT:
222 m = reAccountValue.matcher(line);
223 boolean match_found = false;
228 String value = m.group(1);
229 String currency = m.group(2);
230 if (currency == null) currency = "";
231 value = value.replace(',', '.');
232 L("curr=" + currency + ", value=" + value);
233 profile.storeAccountValue(db, lastAccount.getName(), currency,
234 Float.valueOf(value));
235 lastAccount.addAmount(Float.parseFloat(value), currency);
239 state = ParserState.EXPECTING_ACCOUNT;
240 L("→ expecting account");
245 case EXPECTING_TRANSACTION:
246 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
247 m = reTransactionStart.matcher(line);
249 transactionId = Integer.valueOf(m.group(1));
250 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
251 L(String.format("found transaction %d → expecting description",
253 progress.setProgress(++processedTransactionCount);
254 if (maxTransactionId < transactionId)
255 maxTransactionId = transactionId;
256 if ((progress.getTotal() == Progress.INDETERMINATE) ||
257 (progress.getTotal() < transactionId))
258 progress.setTotal(transactionId);
259 publishProgress(progress);
261 m = reEnd.matcher(line);
263 L("--- transaction value complete ---");
268 case EXPECTING_TRANSACTION_DESCRIPTION:
269 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
270 m = reTransactionDescription.matcher(line);
272 if (transactionId == 0) throw new TransactionParserException(
273 "Transaction Id is 0 while expecting " + "description");
275 String date = m.group(1);
277 int equalsIndex = date.indexOf('=');
278 if (equalsIndex >= 0)
279 date = date.substring(equalsIndex + 1);
280 transaction = new LedgerTransaction(transactionId, date,
283 catch (ParseException e) {
285 return String.format("Error parsing date '%s'", date);
287 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
288 L(String.format("transaction %d created for %s (%s) →" +
289 " expecting details", transactionId, date,
294 case EXPECTING_TRANSACTION_DETAILS:
295 if (line.isEmpty()) {
296 // transaction data collected
297 if (transaction.existsInDb(db)) {
298 profile.markTransactionAsPresent(db, transaction);
299 matchedTransactionsCount++;
301 if (matchedTransactionsCount ==
302 MATCHING_TRANSACTIONS_LIMIT)
304 profile.markTransactionsBeforeTransactionAsPresent(db,
306 progress.setTotal(progress.getProgress());
307 publishProgress(progress);
312 profile.storeTransaction(db, transaction);
313 matchedTransactionsCount = 0;
314 progress.setTotal(maxTransactionId);
317 state = ParserState.EXPECTING_TRANSACTION;
318 L(String.format("transaction %s saved → expecting transaction",
319 transaction.getId()));
320 transaction.finishLoading();
322 // sounds like a good idea, but transaction-1 may not be the first one chronologically
323 // for example, when you add the initial seeding transaction after entering some others
324 // if (transactionId == 1) {
325 // L("This was the initial transaction. Terminating " +
331 m = reTransactionDetails.matcher(line);
333 String acc_name = m.group(1);
334 String amount = m.group(2);
335 String currency = m.group(3);
336 if (currency == null) currency = "";
337 amount = amount.replace(',', '.');
338 transaction.addAccount(
339 new LedgerTransactionAccount(acc_name,
340 Float.valueOf(amount), currency));
341 L(String.format("%d: %s = %s", transaction.getId(),
344 else throw new IllegalStateException(String.format(
345 "Can't parse transaction %d " + "details: %s",
346 transactionId, line));
350 throw new RuntimeException(
351 String.format("Unknown parser updating %s", state.name()));
357 profile.deleteNotPresentTransactions(db);
358 db.setTransactionSuccessful();
360 profile.setLastUpdateStamp();
370 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
371 db.execSQL("UPDATE transactions set keep=0 where profile=?",
372 new String[]{profile.getUuid()});
373 db.execSQL("update account_values set keep=0 where profile=?;",
374 new String[]{profile.getUuid()});
375 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
377 private boolean retrieveAccountList(MobileLedgerProfile profile)
378 throws IOException, HTTPException {
379 Progress progress = new Progress();
381 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
382 http.setAllowUserInteraction(false);
383 switch (http.getResponseCode()) {
389 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
391 publishProgress(progress);
392 SQLiteDatabase db = MLDB.getDatabase();
393 ArrayList<LedgerAccount> accountList = new ArrayList<>();
394 boolean listFilledOK = false;
395 try (InputStream resp = http.getInputStream()) {
396 if (http.getResponseCode() != 200)
397 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
399 db.beginTransaction();
401 profile.markAccountsAsNotPresent(db);
403 AccountListParser parser = new AccountListParser(resp);
405 LedgerAccount prevAccount = null;
409 ParsedLedgerAccount parsedAccount = parser.nextAccount();
410 if (parsedAccount == null) break;
412 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
413 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
414 else acc.removeAmounts();
416 profile.storeAccount(db, acc);
417 String lastCurrency = null;
418 float lastCurrencyAmount = 0;
419 for (ParsedBalance b : parsedAccount.getAibalance()) {
420 final String currency = b.getAcommodity();
421 final float amount = b.getAquantity().asFloat();
422 if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
424 if (lastCurrency != null) {
425 profile.storeAccountValue(db, acc.getName(), lastCurrency,
427 acc.addAmount(lastCurrencyAmount, lastCurrency);
429 lastCurrency = currency;
430 lastCurrencyAmount = amount;
433 if (lastCurrency != null) {
434 profile.storeAccountValue(db, acc.getName(), lastCurrency,
436 acc.addAmount(lastCurrencyAmount, lastCurrency);
439 if (acc.isVisible(accountList)) accountList.add(acc);
441 if (prevAccount != null) {
442 prevAccount.setHasSubAccounts(
443 acc.getName().startsWith(prevAccount.getName() + ":"));
450 profile.deleteNotPresentAccounts(db);
452 db.setTransactionSuccessful();
459 // should not be set in the DB transaction, because of a possible deadlock
460 // with the main and DbOpQueueRunner threads
461 if (listFilledOK) Data.accounts.setList(accountList);
465 private boolean retrieveTransactionList(MobileLedgerProfile profile)
466 throws IOException, ParseException, HTTPException {
467 Progress progress = new Progress();
468 int maxTransactionId = Progress.INDETERMINATE;
470 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
471 http.setAllowUserInteraction(false);
472 publishProgress(progress);
473 switch (http.getResponseCode()) {
479 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
481 SQLiteDatabase db = MLDB.getDatabase();
482 try (InputStream resp = http.getInputStream()) {
483 if (http.getResponseCode() != 200)
484 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
486 db.beginTransaction();
488 profile.markTransactionsAsNotPresent(db);
490 int matchedTransactionsCount = 0;
491 TransactionListParser parser = new TransactionListParser(resp);
493 int processedTransactionCount = 0;
497 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
499 if (parsedTransaction == null) break;
500 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
501 if (transaction.existsInDb(db)) {
502 profile.markTransactionAsPresent(db, transaction);
503 matchedTransactionsCount++;
505 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
506 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
507 progress.setTotal(progress.getProgress());
508 publishProgress(progress);
509 db.setTransactionSuccessful();
510 profile.setLastUpdateStamp();
515 profile.storeTransaction(db, transaction);
516 matchedTransactionsCount = 0;
517 progress.setTotal(maxTransactionId);
520 if ((progress.getTotal() == Progress.INDETERMINATE) ||
521 (progress.getTotal() < transaction.getId()))
522 progress.setTotal(transaction.getId());
524 progress.setProgress(++processedTransactionCount);
525 publishProgress(progress);
529 profile.deleteNotPresentTransactions(db);
531 db.setTransactionSuccessful();
532 profile.setLastUpdateStamp();
541 @SuppressLint("DefaultLocale")
543 protected String doInBackground(Void... params) {
544 MobileLedgerProfile profile = Data.profile.get();
545 Data.backgroundTaskCount.incrementAndGet();
547 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
548 return retrieveTransactionListLegacy(profile);
551 catch (MalformedURLException e) {
553 return "Invalid server URL";
555 catch (HTTPException e) {
557 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
559 catch (IOException e) {
561 return e.getLocalizedMessage();
563 catch (ParseException e) {
565 return "Network error";
567 catch (OperationCanceledException e) {
569 return "Operation cancelled";
572 Data.backgroundTaskCount.decrementAndGet();
575 private MainActivity getContext() {
576 return contextRef.get();
578 private void throwIfCancelled() {
579 if (isCancelled()) throw new OperationCanceledException(null);
582 private enum ParserState {
583 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
584 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
587 public class Progress {
588 public static final int INDETERMINATE = -1;
589 private int progress;
592 this(INDETERMINATE, INDETERMINATE);
594 Progress(int progress, int total) {
595 this.progress = progress;
598 public int getProgress() {
601 protected void setProgress(int progress) {
602 this.progress = progress;
604 public int getTotal() {
607 protected void setTotal(int total) {
612 private class TransactionParserException extends IllegalStateException {
613 TransactionParserException(String message) {