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.loadAccount(acct_name);
173 if (lastAccount == null) {
174 lastAccount = new LedgerAccount(acct_name);
175 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.setHidden(lastAccount.isHidden());
193 if (!onlyStarred || !acc.isHidden())
194 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.isHidden())
202 accountList.add(lastAccount);
203 accountNames.put(acct_name, null);
205 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
206 L("→ expecting account amount");
210 case EXPECTING_ACCOUNT_AMOUNT:
211 m = reAccountValue.matcher(line);
212 boolean match_found = false;
217 String value = m.group(1);
218 String currency = m.group(2);
219 if (currency == null) currency = "";
220 value = value.replace(',', '.');
221 L("curr=" + currency + ", value=" + value);
222 profile.storeAccountValue(db, lastAccount.getName(), currency,
223 Float.valueOf(value));
224 lastAccount.addAmount(Float.parseFloat(value), currency);
228 state = ParserState.EXPECTING_ACCOUNT;
229 L("→ expecting account");
234 case EXPECTING_TRANSACTION:
235 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
236 m = reTransactionStart.matcher(line);
238 transactionId = Integer.valueOf(m.group(1));
239 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
240 L(String.format("found transaction %d → expecting description",
242 progress.setProgress(++processedTransactionCount);
243 if (maxTransactionId < transactionId)
244 maxTransactionId = transactionId;
245 if ((progress.getTotal() == Progress.INDETERMINATE) ||
246 (progress.getTotal() < transactionId))
247 progress.setTotal(transactionId);
248 publishProgress(progress);
250 m = reEnd.matcher(line);
252 L("--- transaction value complete ---");
257 case EXPECTING_TRANSACTION_DESCRIPTION:
258 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
259 m = reTransactionDescription.matcher(line);
261 if (transactionId == 0) throw new TransactionParserException(
262 "Transaction Id is 0 while expecting " + "description");
264 String date = m.group(1);
266 int equalsIndex = date.indexOf('=');
267 if (equalsIndex >= 0)
268 date = date.substring(equalsIndex + 1);
269 transaction = new LedgerTransaction(transactionId, date,
272 catch (ParseException e) {
274 return String.format("Error parsing date '%s'", date);
276 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
277 L(String.format("transaction %d created for %s (%s) →" +
278 " expecting details", transactionId, date,
283 case EXPECTING_TRANSACTION_DETAILS:
284 if (line.isEmpty()) {
285 // transaction data collected
286 if (transaction.existsInDb(db)) {
287 profile.markTransactionAsPresent(db, transaction);
288 matchedTransactionsCount++;
290 if (matchedTransactionsCount ==
291 MATCHING_TRANSACTIONS_LIMIT)
293 profile.markTransactionsBeforeTransactionAsPresent(db,
295 progress.setTotal(progress.getProgress());
296 publishProgress(progress);
301 profile.storeTransaction(db, transaction);
302 matchedTransactionsCount = 0;
303 progress.setTotal(maxTransactionId);
306 state = ParserState.EXPECTING_TRANSACTION;
307 L(String.format("transaction %s saved → expecting transaction",
308 transaction.getId()));
309 transaction.finishLoading();
311 // sounds like a good idea, but transaction-1 may not be the first one chronologically
312 // for example, when you add the initial seeding transaction after entering some others
313 // if (transactionId == 1) {
314 // L("This was the initial transaction. Terminating " +
320 m = reTransactionDetails.matcher(line);
322 String acc_name = m.group(1);
323 String amount = m.group(2);
324 String currency = m.group(3);
325 if (currency == null) currency = "";
326 amount = amount.replace(',', '.');
327 transaction.addAccount(
328 new LedgerTransactionAccount(acc_name,
329 Float.valueOf(amount), currency));
330 L(String.format("%d: %s = %s", transaction.getId(),
333 else throw new IllegalStateException(String.format(
334 "Can't parse transaction %d " + "details: %s",
335 transactionId, line));
339 throw new RuntimeException(
340 String.format("Unknown parser updating %s", state.name()));
346 profile.deleteNotPresentTransactions(db);
347 db.setTransactionSuccessful();
349 profile.setLastUpdateStamp();
359 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
360 db.execSQL("UPDATE transactions set keep=0 where profile=?",
361 new String[]{profile.getUuid()});
362 db.execSQL("update account_values set keep=0 where profile=?;",
363 new String[]{profile.getUuid()});
364 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
366 private boolean retrieveAccountList(MobileLedgerProfile profile)
367 throws IOException, HTTPException {
368 Progress progress = new Progress();
370 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
371 http.setAllowUserInteraction(false);
372 switch (http.getResponseCode()) {
378 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
380 publishProgress(progress);
381 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
382 try (InputStream resp = http.getInputStream()) {
383 if (http.getResponseCode() != 200)
384 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
386 db.beginTransaction();
388 profile.markAccountsAsNotPresent(db);
390 AccountListParser parser = new AccountListParser(resp);
391 ArrayList<LedgerAccount> accountList = new ArrayList<>();
395 ParsedLedgerAccount parsedAccount = parser.nextAccount();
396 if (parsedAccount == null) break;
398 LedgerAccount acc = new LedgerAccount(parsedAccount.getAname());
399 profile.storeAccount(db, acc);
400 for (ParsedBalance b : parsedAccount.getAebalance()) {
401 profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
402 b.getAquantity().asFloat());
405 accountList.add(acc);
409 profile.deleteNotPresentAccounts(db);
411 db.setTransactionSuccessful();
412 Data.accounts.set(accountList);
422 private boolean retrieveTransactionList(MobileLedgerProfile profile)
423 throws IOException, ParseException, HTTPException {
424 Progress progress = new Progress();
425 int maxTransactionId = Progress.INDETERMINATE;
427 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
428 http.setAllowUserInteraction(false);
429 publishProgress(progress);
430 switch (http.getResponseCode()) {
436 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
438 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
439 try (InputStream resp = http.getInputStream()) {
440 if (http.getResponseCode() != 200)
441 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
443 db.beginTransaction();
445 profile.markTransactionsAsNotPresent(db);
447 int matchedTransactionsCount = 0;
448 TransactionListParser parser = new TransactionListParser(resp);
450 int processedTransactionCount = 0;
454 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
456 if (parsedTransaction == null) break;
457 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
458 if (transaction.existsInDb(db)) {
459 profile.markTransactionAsPresent(db, transaction);
460 matchedTransactionsCount++;
462 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
463 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
464 progress.setTotal(progress.getProgress());
465 publishProgress(progress);
466 db.setTransactionSuccessful();
467 profile.setLastUpdateStamp();
472 profile.storeTransaction(db, transaction);
473 matchedTransactionsCount = 0;
474 progress.setTotal(maxTransactionId);
477 if ((progress.getTotal() == Progress.INDETERMINATE) ||
478 (progress.getTotal() < transaction.getId()))
479 progress.setTotal(transaction.getId());
481 progress.setProgress(++processedTransactionCount);
482 publishProgress(progress);
486 profile.deleteNotPresentTransactions(db);
488 db.setTransactionSuccessful();
489 profile.setLastUpdateStamp();
499 @SuppressLint("DefaultLocale")
501 protected String doInBackground(Void... params) {
502 MobileLedgerProfile profile = Data.profile.get();
503 Data.backgroundTaskCount.incrementAndGet();
505 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
506 return retrieveTransactionListLegacy(profile);
509 catch (MalformedURLException e) {
511 return "Invalid server URL";
513 catch (HTTPException e) {
515 return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
517 catch (IOException e) {
519 return "Parse error";
521 catch (ParseException e) {
523 return "Network error";
525 catch (OperationCanceledException e) {
527 return "Operation cancelled";
530 Data.backgroundTaskCount.decrementAndGet();
533 private MainActivity getContext() {
534 return contextRef.get();
536 private void throwIfCancelled() {
537 if (isCancelled()) throw new OperationCanceledException(null);
540 private enum ParserState {
541 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
542 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
545 public class Progress {
546 public static final int INDETERMINATE = -1;
547 private int progress;
550 this(INDETERMINATE, INDETERMINATE);
552 Progress(int progress, int total) {
553 this.progress = progress;
556 public int getProgress() {
559 protected void setProgress(int progress) {
560 this.progress = progress;
562 public int getTotal() {
565 protected void setTotal(int total) {
570 private class TransactionParserException extends IllegalStateException {
571 TransactionParserException(String message) {