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 {
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;
116 boolean onlyStarred = Data.optShowOnlyStarred.get();
118 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
119 http.setAllowUserInteraction(false);
120 publishProgress(progress);
121 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
122 try (InputStream resp = http.getInputStream()) {
123 if (http.getResponseCode() != 200)
124 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
125 db.beginTransaction();
127 prepareDbForRetrieval(db, profile);
129 int matchedTransactionsCount = 0;
132 ParserState state = ParserState.EXPECTING_ACCOUNT;
135 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
137 int processedTransactionCount = 0;
138 int transactionId = 0;
139 LedgerTransaction transaction = null;
141 while ((line = buf.readLine()) != null) {
144 m = reComment.matcher(line);
146 // TODO: comments are ignored for now
147 Log.v("transaction-parser", "Ignoring comment");
150 //L(String.format("State is %d", updating));
152 case EXPECTING_ACCOUNT:
153 if (line.equals("<h2>General Journal</h2>")) {
154 state = ParserState.EXPECTING_TRANSACTION;
155 L("→ expecting transaction");
156 Data.accounts.set(accountList);
159 m = reAccountName.matcher(line);
161 String acct_encoded = m.group(1);
162 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
163 acct_name = acct_name.replace("\"", "");
164 L(String.format("found account: %s", acct_name));
166 lastAccount = profile.loadAccount(acct_name);
167 if (lastAccount == null) {
168 lastAccount = new LedgerAccount(acct_name);
169 profile.storeAccount(db, lastAccount);
172 // make sure the parent account(s) are present,
173 // synthesising them if necessary
174 String parentName = lastAccount.getParentName();
175 if (parentName != null) {
176 Stack<String> toAppend = new Stack<>();
177 while (parentName != null) {
178 if (accountNames.containsKey(parentName)) break;
179 toAppend.push(parentName);
181 new LedgerAccount(parentName).getParentName();
183 while (!toAppend.isEmpty()) {
184 String aName = toAppend.pop();
185 LedgerAccount acc = new LedgerAccount(aName);
186 acc.setHidden(lastAccount.isHidden());
187 if (!onlyStarred || !acc.isHidden())
188 accountList.add(acc);
189 L(String.format("gap-filling with %s", aName));
190 accountNames.put(aName, null);
191 profile.storeAccount(db, acc);
195 if (!onlyStarred || !lastAccount.isHidden())
196 accountList.add(lastAccount);
197 accountNames.put(acct_name, null);
199 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
200 L("→ expecting account amount");
204 case EXPECTING_ACCOUNT_AMOUNT:
205 m = reAccountValue.matcher(line);
206 boolean match_found = false;
211 String value = m.group(1);
212 String currency = m.group(2);
213 if (currency == null) currency = "";
214 value = value.replace(',', '.');
215 L("curr=" + currency + ", value=" + value);
216 profile.storeAccountValue(db, lastAccount.getName(), currency,
217 Float.valueOf(value));
218 lastAccount.addAmount(Float.parseFloat(value), currency);
222 state = ParserState.EXPECTING_ACCOUNT;
223 L("→ expecting account");
228 case EXPECTING_TRANSACTION:
229 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
230 m = reTransactionStart.matcher(line);
232 transactionId = Integer.valueOf(m.group(1));
233 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
234 L(String.format("found transaction %d → expecting description",
236 progress.setProgress(++processedTransactionCount);
237 if (maxTransactionId < transactionId)
238 maxTransactionId = transactionId;
239 if ((progress.getTotal() == Progress.INDETERMINATE) ||
240 (progress.getTotal() < transactionId))
241 progress.setTotal(transactionId);
242 publishProgress(progress);
244 m = reEnd.matcher(line);
246 L("--- transaction value complete ---");
251 case EXPECTING_TRANSACTION_DESCRIPTION:
252 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
253 m = reTransactionDescription.matcher(line);
255 if (transactionId == 0) throw new TransactionParserException(
256 "Transaction Id is 0 while expecting " + "description");
258 String date = m.group(1);
260 int equalsIndex = date.indexOf('=');
261 if (equalsIndex >= 0)
262 date = date.substring(equalsIndex + 1);
263 transaction = new LedgerTransaction(transactionId, date,
266 catch (ParseException e) {
268 return String.format("Error parsing date '%s'", date);
270 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
271 L(String.format("transaction %d created for %s (%s) →" +
272 " expecting details", transactionId, date,
277 case EXPECTING_TRANSACTION_DETAILS:
278 if (line.isEmpty()) {
279 // transaction data collected
280 if (transaction.existsInDb(db)) {
281 profile.markTransactionAsPresent(db, transaction);
282 matchedTransactionsCount++;
284 if (matchedTransactionsCount ==
285 MATCHING_TRANSACTIONS_LIMIT)
287 profile.markTransactionsBeforeTransactionAsPresent(db,
289 progress.setTotal(progress.getProgress());
290 publishProgress(progress);
295 profile.storeTransaction(db, transaction);
296 matchedTransactionsCount = 0;
297 progress.setTotal(maxTransactionId);
300 state = ParserState.EXPECTING_TRANSACTION;
301 L(String.format("transaction %s saved → expecting transaction",
302 transaction.getId()));
303 transaction.finishLoading();
305 // sounds like a good idea, but transaction-1 may not be the first one chronologically
306 // for example, when you add the initial seeding transaction after entering some others
307 // if (transactionId == 1) {
308 // L("This was the initial transaction. Terminating " +
314 m = reTransactionDetails.matcher(line);
316 String acc_name = m.group(1);
317 String amount = m.group(2);
318 String currency = m.group(3);
319 if (currency == null) currency = "";
320 amount = amount.replace(',', '.');
321 transaction.addAccount(
322 new LedgerTransactionAccount(acc_name,
323 Float.valueOf(amount), currency));
324 L(String.format("%d: %s = %s", transaction.getId(),
327 else throw new IllegalStateException(String.format(
328 "Can't parse transaction %d " + "details: %s",
329 transactionId, line));
333 throw new RuntimeException(
334 String.format("Unknown parser updating %s", state.name()));
340 profile.deleteNotPresentTransactions(db);
341 db.setTransactionSuccessful();
343 profile.setLastUpdateStamp();
353 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
354 db.execSQL("UPDATE transactions set keep=0 where profile=?",
355 new String[]{profile.getUuid()});
356 db.execSQL("update account_values set keep=0 where profile=?;",
357 new String[]{profile.getUuid()});
358 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
360 private boolean retrieveAccountList(MobileLedgerProfile profile)
361 throws IOException, HTTPException {
362 Progress progress = new Progress();
364 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
365 http.setAllowUserInteraction(false);
366 switch (http.getResponseCode()) {
372 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
374 publishProgress(progress);
375 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
376 try (InputStream resp = http.getInputStream()) {
377 if (http.getResponseCode() != 200)
378 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
380 db.beginTransaction();
382 profile.markAccountsAsNotPresent(db);
384 AccountListParser parser = new AccountListParser(resp);
385 ArrayList<LedgerAccount> accountList = new ArrayList<>();
389 ParsedLedgerAccount parsedAccount = parser.nextAccount();
390 if (parsedAccount == null) break;
392 LedgerAccount acc = new LedgerAccount(parsedAccount.getAname());
393 profile.storeAccount(db, acc);
394 for (ParsedBalance b : parsedAccount.getAebalance()) {
395 profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
396 b.getAquantity().asFloat());
399 accountList.add(acc);
403 profile.deleteNotPresentAccounts(db);
405 db.setTransactionSuccessful();
406 Data.accounts.set(accountList);
416 private boolean retrieveTransactionList(MobileLedgerProfile profile)
417 throws IOException, ParseException, HTTPException {
418 Progress progress = new Progress();
419 int maxTransactionId = Progress.INDETERMINATE;
421 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
422 http.setAllowUserInteraction(false);
423 publishProgress(progress);
424 switch (http.getResponseCode()) {
430 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
432 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
433 try (InputStream resp = http.getInputStream()) {
434 if (http.getResponseCode() != 200)
435 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
437 db.beginTransaction();
439 profile.markTransactionsAsNotPresent(db);
441 int matchedTransactionsCount = 0;
442 TransactionListParser parser = new TransactionListParser(resp);
444 int processedTransactionCount = 0;
448 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
450 if (parsedTransaction == null) break;
451 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
452 if (transaction.existsInDb(db)) {
453 profile.markTransactionAsPresent(db, transaction);
454 matchedTransactionsCount++;
456 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
457 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
458 progress.setTotal(progress.getProgress());
459 publishProgress(progress);
460 db.setTransactionSuccessful();
461 profile.setLastUpdateStamp();
466 profile.storeTransaction(db, transaction);
467 matchedTransactionsCount = 0;
468 progress.setTotal(maxTransactionId);
471 progress.setProgress(++processedTransactionCount);
472 publishProgress(progress);
476 profile.deleteNotPresentTransactions(db);
478 db.setTransactionSuccessful();
479 profile.setLastUpdateStamp();
489 @SuppressLint("DefaultLocale")
491 protected String doInBackground(Void... params) {
492 MobileLedgerProfile profile = Data.profile.get();
493 Data.backgroundTaskCount.incrementAndGet();
495 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
496 return retrieveTransactionListLegacy(profile);
499 catch (MalformedURLException e) {
501 return "Invalid server URL";
503 catch (HTTPException e) {
505 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
507 catch (IOException e) {
509 return "Parse error";
511 catch (ParseException e) {
513 return "Network error";
515 catch (OperationCanceledException e) {
517 return "Operation cancelled";
520 Data.backgroundTaskCount.decrementAndGet();
523 private MainActivity getContext() {
524 return contextRef.get();
526 private void throwIfCancelled() {
527 if (isCancelled()) throw new OperationCanceledException(null);
530 private enum ParserState {
531 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
532 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
535 public class Progress {
536 public static final int INDETERMINATE = -1;
537 private int progress;
540 this(INDETERMINATE, INDETERMINATE);
542 Progress(int progress, int total) {
543 this.progress = progress;
546 public int getProgress() {
549 protected void setProgress(int progress) {
550 this.progress = progress;
552 public int getTotal() {
555 protected void setTotal(int total) {
560 private class TransactionParserException extends IllegalStateException {
561 TransactionParserException(String message) {