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.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) throws IOException {
361 Progress progress = new Progress();
363 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
364 http.setAllowUserInteraction(false);
365 publishProgress(progress);
366 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
367 try (InputStream resp = http.getInputStream()) {
368 if (http.getResponseCode() != 200)
369 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
371 db.beginTransaction();
373 profile.markAccountsAsNotPresent(db);
375 AccountListParser parser = new AccountListParser(resp);
376 ArrayList<LedgerAccount> accountList = new ArrayList<>();
380 ParsedLedgerAccount parsedAccount = parser.nextAccount();
381 if (parsedAccount == null) break;
383 LedgerAccount acc = new LedgerAccount(parsedAccount.getAname());
384 profile.storeAccount(db, acc);
385 for (ParsedBalance b : parsedAccount.getAebalance()) {
386 profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
387 b.getAquantity().asFloat());
390 accountList.add(acc);
394 profile.deleteNotPresentAccounts(db);
396 db.setTransactionSuccessful();
397 Data.accounts.set(accountList);
407 private boolean retrieveTransactionList(MobileLedgerProfile profile)
408 throws IOException, ParseException {
409 Progress progress = new Progress();
410 int maxTransactionId = Progress.INDETERMINATE;
412 HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
413 http.setAllowUserInteraction(false);
414 publishProgress(progress);
415 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
416 try (InputStream resp = http.getInputStream()) {
417 if (http.getResponseCode() != 200)
418 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
420 db.beginTransaction();
422 profile.markTransactionsAsNotPresent(db);
424 int matchedTransactionsCount = 0;
425 TransactionListParser parser = new TransactionListParser(resp);
427 int processedTransactionCount = 0;
431 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
433 if (parsedTransaction == null) break;
434 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
435 if (transaction.existsInDb(db)) {
436 profile.markTransactionAsPresent(db, transaction);
437 matchedTransactionsCount++;
439 if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
440 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
441 progress.setTotal(progress.getProgress());
442 publishProgress(progress);
443 db.setTransactionSuccessful();
444 profile.setLastUpdateStamp();
449 profile.storeTransaction(db, transaction);
450 matchedTransactionsCount = 0;
451 progress.setTotal(maxTransactionId);
454 progress.setProgress(++processedTransactionCount);
455 publishProgress(progress);
459 profile.deleteNotPresentTransactions(db);
461 db.setTransactionSuccessful();
462 profile.setLastUpdateStamp();
472 @SuppressLint("DefaultLocale")
474 protected String doInBackground(Void... params) {
475 MobileLedgerProfile profile = Data.profile.get();
476 Data.backgroundTaskCount.incrementAndGet();
478 if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
479 return retrieveTransactionListLegacy(profile);
482 catch (MalformedURLException e) {
484 return "Invalid server URL";
486 catch (FileNotFoundException e) {
488 return "Invalid user name or password";
490 catch (IOException e) {
492 return "Network error";
494 catch (ParseException e) {
496 return "Network error";
498 catch (OperationCanceledException e) {
500 return "Operation cancelled";
503 Data.backgroundTaskCount.decrementAndGet();
506 private MainActivity getContext() {
507 return contextRef.get();
509 private void throwIfCancelled() {
510 if (isCancelled()) throw new OperationCanceledException(null);
513 private enum ParserState {
514 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
515 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
518 public class Progress {
519 public static final int INDETERMINATE = -1;
520 private int progress;
523 this(INDETERMINATE, INDETERMINATE);
525 Progress(int progress, int total) {
526 this.progress = progress;
529 public int getProgress() {
532 protected void setProgress(int progress) {
533 this.progress = progress;
535 public int getTotal() {
538 protected void setTotal(int total) {
543 private class TransactionParserException extends IllegalStateException {
544 TransactionParserException(String message) {