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.json.AccountListParser;
27 import net.ktnx.mobileledger.json.ParsedBalance;
28 import net.ktnx.mobileledger.json.ParsedLedgerAccount;
29 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
30 import net.ktnx.mobileledger.json.TransactionListParser;
31 import net.ktnx.mobileledger.model.Data;
32 import net.ktnx.mobileledger.model.LedgerAccount;
33 import net.ktnx.mobileledger.model.LedgerTransaction;
34 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
35 import net.ktnx.mobileledger.model.MobileLedgerProfile;
36 import net.ktnx.mobileledger.ui.activity.MainActivity;
37 import net.ktnx.mobileledger.utils.MLDB;
38 import net.ktnx.mobileledger.utils.NetworkUtil;
40 import java.io.BufferedReader;
41 import java.io.FileNotFoundException;
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.Date;
53 import java.util.HashMap;
54 import java.util.Stack;
55 import java.util.regex.Matcher;
56 import java.util.regex.Pattern;
59 public class RetrieveTransactionsTask
60 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
61 private static final int MATCHING_TRANSACTIONS_LIMIT = 50;
62 private static final Pattern reComment = Pattern.compile("^\\s*;");
63 private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
64 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
65 private static final Pattern reTransactionDescription =
66 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
67 private static final Pattern reTransactionDetails =
68 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
69 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
70 private WeakReference<MainActivity> contextRef;
73 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
74 private Pattern reAccountValue = Pattern.compile(
75 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
76 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
77 this.contextRef = contextRef;
79 private static void L(String msg) {
80 //Log.d("transaction-parser", msg);
83 protected void onProgressUpdate(Progress... values) {
84 super.onProgressUpdate(values);
85 MainActivity context = getContext();
86 if (context == null) return;
87 context.onRetrieveProgress(values[0]);
90 protected void onPreExecute() {
92 MainActivity context = getContext();
93 if (context == null) return;
94 context.onRetrieveStart();
97 protected void onPostExecute(String error) {
98 super.onPostExecute(error);
99 MainActivity context = getContext();
100 if (context == null) return;
101 context.onRetrieveDone(error);
104 protected void onCancelled() {
106 MainActivity context = getContext();
107 if (context == null) return;
108 context.onRetrieveDone(null);
110 private String retrieveTransactionListLegacy(MobileLedgerProfile profile)
111 throws IOException, ParseException {
112 Progress progress = new Progress();
113 int maxTransactionId = Progress.INDETERMINATE;
114 ArrayList<LedgerAccount> accountList = new ArrayList<>();
115 HashMap<String, Void> accountNames = new HashMap<>();
116 LedgerAccount lastAccount = null;
117 boolean onlyStarred = Data.optShowOnlyStarred.get();
119 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
120 http.setAllowUserInteraction(false);
121 publishProgress(progress);
122 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
123 try (InputStream resp = http.getInputStream()) {
124 if (http.getResponseCode() != 200)
125 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
126 db.beginTransaction();
128 prepareDbForRetrieval(db, profile);
130 int matchedTransactionsCount = 0;
133 ParserState state = ParserState.EXPECTING_ACCOUNT;
136 new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
138 int processedTransactionCount = 0;
139 int transactionId = 0;
140 LedgerTransaction transaction = null;
142 while ((line = buf.readLine()) != null) {
145 m = reComment.matcher(line);
147 // TODO: comments are ignored for now
148 Log.v("transaction-parser", "Ignoring comment");
151 //L(String.format("State is %d", updating));
153 case EXPECTING_ACCOUNT:
154 if (line.equals("<h2>General Journal</h2>")) {
155 state = ParserState.EXPECTING_TRANSACTION;
156 L("→ expecting transaction");
157 Data.accounts.set(accountList);
160 m = reAccountName.matcher(line);
162 String acct_encoded = m.group(1);
163 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
164 acct_name = acct_name.replace("\"", "");
165 L(String.format("found account: %s", acct_name));
167 lastAccount = profile.loadAccount(acct_name);
168 if (lastAccount == null) {
169 lastAccount = new LedgerAccount(acct_name);
170 profile.storeAccount(lastAccount);
173 // make sure the parent account(s) are present,
174 // synthesising them if necessary
175 String parentName = lastAccount.getParentName();
176 if (parentName != null) {
177 Stack<String> toAppend = new Stack<>();
178 while (parentName != null) {
179 if (accountNames.containsKey(parentName)) break;
180 toAppend.push(parentName);
182 new LedgerAccount(parentName).getParentName();
184 while (!toAppend.isEmpty()) {
185 String aName = toAppend.pop();
186 LedgerAccount acc = new LedgerAccount(aName);
187 acc.setHidden(lastAccount.isHidden());
188 if (!onlyStarred || !acc.isHidden())
189 accountList.add(acc);
190 L(String.format("gap-filling with %s", aName));
191 accountNames.put(aName, null);
192 profile.storeAccount(acc);
196 if (!onlyStarred || !lastAccount.isHidden())
197 accountList.add(lastAccount);
198 accountNames.put(acct_name, null);
200 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
201 L("→ expecting account amount");
205 case EXPECTING_ACCOUNT_AMOUNT:
206 m = reAccountValue.matcher(line);
207 boolean match_found = false;
212 String value = m.group(1);
213 String currency = m.group(2);
214 if (currency == null) currency = "";
215 value = value.replace(',', '.');
216 L("curr=" + currency + ", value=" + value);
217 profile.storeAccountValue(lastAccount.getName(), currency,
218 Float.valueOf(value));
219 lastAccount.addAmount(Float.parseFloat(value), currency);
223 state = ParserState.EXPECTING_ACCOUNT;
224 L("→ expecting account");
229 case EXPECTING_TRANSACTION:
230 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
231 m = reTransactionStart.matcher(line);
233 transactionId = Integer.valueOf(m.group(1));
234 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
235 L(String.format("found transaction %d → expecting description",
237 progress.setProgress(++processedTransactionCount);
238 if (maxTransactionId < transactionId)
239 maxTransactionId = transactionId;
240 if ((progress.getTotal() == Progress.INDETERMINATE) ||
241 (progress.getTotal() < transactionId))
242 progress.setTotal(transactionId);
243 publishProgress(progress);
245 m = reEnd.matcher(line);
247 L("--- transaction value complete ---");
252 case EXPECTING_TRANSACTION_DESCRIPTION:
253 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
254 m = reTransactionDescription.matcher(line);
256 if (transactionId == 0) throw new TransactionParserException(
257 "Transaction Id is 0 while expecting " + "description");
259 String date = m.group(1);
261 int equalsIndex = date.indexOf('=');
262 if (equalsIndex >= 0)
263 date = date.substring(equalsIndex + 1);
264 transaction = new LedgerTransaction(transactionId, date,
267 catch (ParseException e) {
269 return String.format("Error parsing date '%s'", date);
271 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
272 L(String.format("transaction %d created for %s (%s) →" +
273 " expecting details", transactionId, date,
278 case EXPECTING_TRANSACTION_DETAILS:
279 if (line.isEmpty()) {
280 // transaction data collected
281 if (transaction.existsInDb(db)) {
282 profile.markTransactionAsPresent(db, transaction);
283 matchedTransactionsCount++;
285 if (matchedTransactionsCount ==
286 MATCHING_TRANSACTIONS_LIMIT)
288 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
289 progress.setTotal(progress.getProgress());
290 publishProgress(progress);
295 profile.storeTransaction(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 Log.d("db", "Updating transaction value stamp");
344 Date now = new Date();
345 profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
346 Data.lastUpdateDate.set(now);
356 private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
357 db.execSQL("UPDATE transactions set keep=0 where profile=?",
358 new String[]{profile.getUuid()});
359 db.execSQL("update account_values set keep=0 where profile=?;",
360 new String[]{profile.getUuid()});
361 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
363 private boolean retrieveAccountList(MobileLedgerProfile profile) throws IOException {
364 Progress progress = new Progress();
366 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
367 http.setAllowUserInteraction(false);
368 publishProgress(progress);
369 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
370 try (InputStream resp = http.getInputStream()) {
371 if (http.getResponseCode() != 200)
372 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
374 db.beginTransaction();
376 profile.markAccountsAsNotPresent(db);
378 AccountListParser parser = new AccountListParser(resp);
381 ParsedLedgerAccount parsedAccount = parser.nextAccount();
382 if (parsedAccount == null) break;
384 LedgerAccount acc = new LedgerAccount(parsedAccount.getAname());
385 profile.storeAccount(acc);
386 for (ParsedBalance b : parsedAccount.getAebalance()) {
387 profile.storeAccountValue(acc.getName(), b.getAcommodity(),
388 b.getAquantity().asFloat());
392 profile.deleteNotPresentAccounts(db);
393 db.setTransactionSuccessful();
403 private boolean retrieveTransactionList(MobileLedgerProfile profile)
404 throws IOException, ParseException {
405 Progress progress = new Progress();
406 int maxTransactionId = Progress.INDETERMINATE;
408 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
409 http.setAllowUserInteraction(false);
410 publishProgress(progress);
411 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
412 try (InputStream resp = http.getInputStream()) {
413 if (http.getResponseCode() != 200)
414 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
415 db.beginTransaction();
417 profile.markTransactionsAsNotPresent(db);
419 int matchedTransactionsCount = 0;
420 TransactionListParser parser = new TransactionListParser(resp);
422 int processedTransactionCount = 0;
425 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
426 if (parsedTransaction == null) break;
427 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
428 if (transaction.existsInDb(db)) {
429 profile.markTransactionAsPresent(db, transaction);
430 matchedTransactionsCount++;
432 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
433 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
434 progress.setTotal(progress.getProgress());
435 publishProgress(progress);
436 db.setTransactionSuccessful();
441 profile.storeTransaction(transaction);
442 matchedTransactionsCount = 0;
443 progress.setTotal(maxTransactionId);
446 progress.setProgress(++processedTransactionCount);
447 publishProgress(progress);
450 profile.deleteNotPresentTransactions(db);
451 db.setTransactionSuccessful();
461 @SuppressLint("DefaultLocale")
463 protected String doInBackground(Void... params) {
464 MobileLedgerProfile profile = Data.profile.get();
465 Data.backgroundTaskCount.incrementAndGet();
467 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
468 return retrieveTransactionListLegacy(profile);
471 catch (MalformedURLException e) {
473 return "Invalid server URL";
475 catch (FileNotFoundException e) {
477 return "Invalid user name or password";
479 catch (IOException e) {
481 return "Network error";
483 catch (ParseException e) {
485 return "Network error";
487 catch (OperationCanceledException e) {
489 return "Operation cancelled";
492 Data.backgroundTaskCount.decrementAndGet();
495 private MainActivity getContext() {
496 return contextRef.get();
498 private void throwIfCancelled() {
499 if (isCancelled()) throw new OperationCanceledException(null);
502 private enum ParserState {
503 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
504 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
507 public class Progress {
508 public static final int INDETERMINATE = -1;
509 private int progress;
512 this(INDETERMINATE, INDETERMINATE);
514 Progress(int progress, int total) {
515 this.progress = progress;
518 public int getProgress() {
521 protected void setProgress(int progress) {
522 this.progress = progress;
524 public int getTotal() {
527 protected void setTotal(int total) {
532 private class TransactionParserException extends IllegalStateException {
533 TransactionParserException(String message) {