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 for (ParsedBalance b : parsedAccount.getAibalance()) {
418 profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
419 b.getAquantity().asFloat());
422 if (acc.isVisible(accountList)) accountList.add(acc);
424 if (prevAccount != null) {
425 prevAccount.setHasSubAccounts(
426 acc.getName().startsWith(prevAccount.getName() + ":"));
433 profile.deleteNotPresentAccounts(db);
435 db.setTransactionSuccessful();
442 // should not be set in the DB transaction, because of a possible deadlock
443 // with the main and DbOpQueueRunner threads
444 if (listFilledOK) Data.accounts.setList(accountList);
448 private boolean retrieveTransactionList(MobileLedgerProfile profile)
449 throws IOException, ParseException, HTTPException {
450 Progress progress = new Progress();
451 int maxTransactionId = Progress.INDETERMINATE;
453 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
454 http.setAllowUserInteraction(false);
455 publishProgress(progress);
456 switch (http.getResponseCode()) {
462 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
464 SQLiteDatabase db = MLDB.getDatabase();
465 try (InputStream resp = http.getInputStream()) {
466 if (http.getResponseCode() != 200)
467 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
469 db.beginTransaction();
471 profile.markTransactionsAsNotPresent(db);
473 int matchedTransactionsCount = 0;
474 TransactionListParser parser = new TransactionListParser(resp);
476 int processedTransactionCount = 0;
480 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
482 if (parsedTransaction == null) break;
483 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
484 if (transaction.existsInDb(db)) {
485 profile.markTransactionAsPresent(db, transaction);
486 matchedTransactionsCount++;
488 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
489 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
490 progress.setTotal(progress.getProgress());
491 publishProgress(progress);
492 db.setTransactionSuccessful();
493 profile.setLastUpdateStamp();
498 profile.storeTransaction(db, transaction);
499 matchedTransactionsCount = 0;
500 progress.setTotal(maxTransactionId);
503 if ((progress.getTotal() == Progress.INDETERMINATE) ||
504 (progress.getTotal() < transaction.getId()))
505 progress.setTotal(transaction.getId());
507 progress.setProgress(++processedTransactionCount);
508 publishProgress(progress);
512 profile.deleteNotPresentTransactions(db);
514 db.setTransactionSuccessful();
515 profile.setLastUpdateStamp();
524 @SuppressLint("DefaultLocale")
526 protected String doInBackground(Void... params) {
527 MobileLedgerProfile profile = Data.profile.get();
528 Data.backgroundTaskCount.incrementAndGet();
530 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
531 return retrieveTransactionListLegacy(profile);
534 catch (MalformedURLException e) {
536 return "Invalid server URL";
538 catch (HTTPException e) {
540 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
542 catch (IOException e) {
544 return e.getLocalizedMessage();
546 catch (ParseException e) {
548 return "Network error";
550 catch (OperationCanceledException e) {
552 return "Operation cancelled";
555 Data.backgroundTaskCount.decrementAndGet();
558 private MainActivity getContext() {
559 return contextRef.get();
561 private void throwIfCancelled() {
562 if (isCancelled()) throw new OperationCanceledException(null);
565 private enum ParserState {
566 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
567 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
570 public class Progress {
571 public static final int INDETERMINATE = -1;
572 private int progress;
575 this(INDETERMINATE, INDETERMINATE);
577 Progress(int progress, int total) {
578 this.progress = progress;
581 public int getProgress() {
584 protected void setProgress(int progress) {
585 this.progress = progress;
587 public int getTotal() {
590 protected void setTotal(int total) {
595 private class TransactionParserException extends IllegalStateException {
596 TransactionParserException(String message) {