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;
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.getWritableDatabase()) {
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 Data.accounts.set(accountList);
165 m = reAccountName.matcher(line);
167 String acct_encoded = m.group(1);
168 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
169 acct_name = acct_name.replace("\"", "");
170 L(String.format("found account: %s", acct_name));
172 lastAccount = profile.tryLoadAccount(db, acct_name);
173 if (lastAccount == null)
174 lastAccount = new LedgerAccount(acct_name);
175 else lastAccount.removeAmounts();
176 profile.storeAccount(db, lastAccount);
178 // make sure the parent account(s) are present,
179 // synthesising them if necessary
180 String parentName = lastAccount.getParentName();
181 if (parentName != null) {
182 Stack<String> toAppend = new Stack<>();
183 while (parentName != null) {
184 if (accountNames.containsKey(parentName)) break;
185 toAppend.push(parentName);
187 new LedgerAccount(parentName).getParentName();
189 while (!toAppend.isEmpty()) {
190 String aName = toAppend.pop();
191 LedgerAccount acc = new LedgerAccount(aName);
192 acc.setHiddenByStar(lastAccount.isHiddenByStar());
193 if ((!onlyStarred || !acc.isHiddenByStar()) &&
194 acc.isVisible(accountList)) accountList.add(acc);
195 L(String.format("gap-filling with %s", aName));
196 accountNames.put(aName, null);
197 profile.storeAccount(db, acc);
201 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
202 lastAccount.isVisible(accountList))
203 accountList.add(lastAccount);
204 accountNames.put(acct_name, null);
206 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
207 L("→ expecting account amount");
211 case EXPECTING_ACCOUNT_AMOUNT:
212 m = reAccountValue.matcher(line);
213 boolean match_found = false;
218 String value = m.group(1);
219 String currency = m.group(2);
220 if (currency == null) currency = "";
221 value = value.replace(',', '.');
222 L("curr=" + currency + ", value=" + value);
223 profile.storeAccountValue(db, lastAccount.getName(), currency,
224 Float.valueOf(value));
225 lastAccount.addAmount(Float.parseFloat(value), currency);
229 state = ParserState.EXPECTING_ACCOUNT;
230 L("→ expecting account");
235 case EXPECTING_TRANSACTION:
236 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
237 m = reTransactionStart.matcher(line);
239 transactionId = Integer.valueOf(m.group(1));
240 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
241 L(String.format("found transaction %d → expecting description",
243 progress.setProgress(++processedTransactionCount);
244 if (maxTransactionId < transactionId)
245 maxTransactionId = transactionId;
246 if ((progress.getTotal() == Progress.INDETERMINATE) ||
247 (progress.getTotal() < transactionId))
248 progress.setTotal(transactionId);
249 publishProgress(progress);
251 m = reEnd.matcher(line);
253 L("--- transaction value complete ---");
258 case EXPECTING_TRANSACTION_DESCRIPTION:
259 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
260 m = reTransactionDescription.matcher(line);
262 if (transactionId == 0) throw new TransactionParserException(
263 "Transaction Id is 0 while expecting " + "description");
265 String date = m.group(1);
267 int equalsIndex = date.indexOf('=');
268 if (equalsIndex >= 0)
269 date = date.substring(equalsIndex + 1);
270 transaction = new LedgerTransaction(transactionId, date,
273 catch (ParseException e) {
275 return String.format("Error parsing date '%s'", date);
277 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
278 L(String.format("transaction %d created for %s (%s) →" +
279 " expecting details", transactionId, date,
284 case EXPECTING_TRANSACTION_DETAILS:
285 if (line.isEmpty()) {
286 // transaction data collected
287 if (transaction.existsInDb(db)) {
288 profile.markTransactionAsPresent(db, transaction);
289 matchedTransactionsCount++;
291 if (matchedTransactionsCount ==
292 MATCHING_TRANSACTIONS_LIMIT)
294 profile.markTransactionsBeforeTransactionAsPresent(db,
296 progress.setTotal(progress.getProgress());
297 publishProgress(progress);
302 profile.storeTransaction(db, transaction);
303 matchedTransactionsCount = 0;
304 progress.setTotal(maxTransactionId);
307 state = ParserState.EXPECTING_TRANSACTION;
308 L(String.format("transaction %s saved → expecting transaction",
309 transaction.getId()));
310 transaction.finishLoading();
312 // sounds like a good idea, but transaction-1 may not be the first one chronologically
313 // for example, when you add the initial seeding transaction after entering some others
314 // if (transactionId == 1) {
315 // L("This was the initial transaction. Terminating " +
321 m = reTransactionDetails.matcher(line);
323 String acc_name = m.group(1);
324 String amount = m.group(2);
325 String currency = m.group(3);
326 if (currency == null) currency = "";
327 amount = amount.replace(',', '.');
328 transaction.addAccount(
329 new LedgerTransactionAccount(acc_name,
330 Float.valueOf(amount), currency));
331 L(String.format("%d: %s = %s", transaction.getId(),
334 else throw new IllegalStateException(String.format(
335 "Can't parse transaction %d " + "details: %s",
336 transactionId, line));
340 throw new RuntimeException(
341 String.format("Unknown parser updating %s", state.name()));
347 profile.deleteNotPresentTransactions(db);
348 db.setTransactionSuccessful();
350 profile.setLastUpdateStamp();
360 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
361 db.execSQL("UPDATE transactions set keep=0 where profile=?",
362 new String[]{profile.getUuid()});
363 db.execSQL("update account_values set keep=0 where profile=?;",
364 new String[]{profile.getUuid()});
365 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
367 private boolean retrieveAccountList(MobileLedgerProfile profile)
368 throws IOException, HTTPException {
369 Progress progress = new Progress();
371 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
372 http.setAllowUserInteraction(false);
373 switch (http.getResponseCode()) {
379 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
381 publishProgress(progress);
382 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
383 try (InputStream resp = http.getInputStream()) {
384 if (http.getResponseCode() != 200)
385 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
387 db.beginTransaction();
389 profile.markAccountsAsNotPresent(db);
391 AccountListParser parser = new AccountListParser(resp);
392 ArrayList<LedgerAccount> accountList = new ArrayList<>();
396 ParsedLedgerAccount parsedAccount = parser.nextAccount();
397 if (parsedAccount == null) break;
399 LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
400 if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
401 else acc.removeAmounts();
403 profile.storeAccount(db, acc);
404 for (ParsedBalance b : parsedAccount.getAebalance()) {
405 profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
406 b.getAquantity().asFloat());
409 if (acc.isVisible(accountList)) accountList.add(acc);
413 profile.deleteNotPresentAccounts(db);
415 db.setTransactionSuccessful();
416 Data.accounts.set(accountList);
426 private boolean retrieveTransactionList(MobileLedgerProfile profile)
427 throws IOException, ParseException, HTTPException {
428 Progress progress = new Progress();
429 int maxTransactionId = Progress.INDETERMINATE;
431 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
432 http.setAllowUserInteraction(false);
433 publishProgress(progress);
434 switch (http.getResponseCode()) {
440 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
442 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
443 try (InputStream resp = http.getInputStream()) {
444 if (http.getResponseCode() != 200)
445 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
447 db.beginTransaction();
449 profile.markTransactionsAsNotPresent(db);
451 int matchedTransactionsCount = 0;
452 TransactionListParser parser = new TransactionListParser(resp);
454 int processedTransactionCount = 0;
458 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
460 if (parsedTransaction == null) break;
461 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
462 if (transaction.existsInDb(db)) {
463 profile.markTransactionAsPresent(db, transaction);
464 matchedTransactionsCount++;
466 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
467 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
468 progress.setTotal(progress.getProgress());
469 publishProgress(progress);
470 db.setTransactionSuccessful();
471 profile.setLastUpdateStamp();
476 profile.storeTransaction(db, transaction);
477 matchedTransactionsCount = 0;
478 progress.setTotal(maxTransactionId);
481 if ((progress.getTotal() == Progress.INDETERMINATE) ||
482 (progress.getTotal() < transaction.getId()))
483 progress.setTotal(transaction.getId());
485 progress.setProgress(++processedTransactionCount);
486 publishProgress(progress);
490 profile.deleteNotPresentTransactions(db);
492 db.setTransactionSuccessful();
493 profile.setLastUpdateStamp();
503 @SuppressLint("DefaultLocale")
505 protected String doInBackground(Void... params) {
506 MobileLedgerProfile profile = Data.profile.get();
507 Data.backgroundTaskCount.incrementAndGet();
509 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
510 return retrieveTransactionListLegacy(profile);
513 catch (MalformedURLException e) {
515 return "Invalid server URL";
517 catch (HTTPException e) {
519 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
521 catch (IOException e) {
523 return e.getLocalizedMessage();
525 catch (ParseException e) {
527 return "Network error";
529 catch (OperationCanceledException e) {
531 return "Operation cancelled";
534 Data.backgroundTaskCount.decrementAndGet();
537 private MainActivity getContext() {
538 return contextRef.get();
540 private void throwIfCancelled() {
541 if (isCancelled()) throw new OperationCanceledException(null);
544 private enum ParserState {
545 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
546 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
549 public class Progress {
550 public static final int INDETERMINATE = -1;
551 private int progress;
554 this(INDETERMINATE, INDETERMINATE);
556 Progress(int progress, int total) {
557 this.progress = progress;
560 public int getProgress() {
563 protected void setProgress(int progress) {
564 this.progress = progress;
566 public int getTotal() {
569 protected void setTotal(int total) {
574 private class TransactionParserException extends IllegalStateException {
575 TransactionParserException(String message) {