2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of Mobile-Ledger.
4 * Mobile-Ledger 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 * Mobile-Ledger 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 Mobile-Ledger. 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.R;
27 import net.ktnx.mobileledger.model.Data;
28 import net.ktnx.mobileledger.model.LedgerAccount;
29 import net.ktnx.mobileledger.model.LedgerTransaction;
30 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
31 import net.ktnx.mobileledger.model.MobileLedgerProfile;
32 import net.ktnx.mobileledger.ui.activity.MainActivity;
33 import net.ktnx.mobileledger.utils.MLDB;
34 import net.ktnx.mobileledger.utils.NetworkUtil;
36 import java.io.BufferedReader;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.InputStreamReader;
41 import java.lang.ref.WeakReference;
42 import java.net.HttpURLConnection;
43 import java.net.MalformedURLException;
44 import java.net.URLDecoder;
45 import java.util.ArrayList;
46 import java.util.Date;
47 import java.util.HashMap;
48 import java.util.Stack;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
53 public class RetrieveTransactionsTask
54 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, Void> {
55 private static final int MATCHING_TRANSACTIONS_LIMIT = 50;
56 private static final Pattern commentPattern = Pattern.compile("^\\s*;");
57 private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
58 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
59 private static final Pattern transactionDescriptionPattern =
60 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
61 private static final Pattern transactionDetailsPattern =
62 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
63 private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
64 private WeakReference<MainActivity> contextRef;
67 private boolean success;
68 private Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
69 private Pattern account_value_re = Pattern.compile(
70 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
71 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
72 this.contextRef = contextRef;
74 private static void L(String msg) {
75 Log.d("transaction-parser", msg);
78 protected void onProgressUpdate(Progress... values) {
79 super.onProgressUpdate(values);
80 MainActivity context = getContext();
81 if (context == null) return;
82 context.onRetrieveProgress(values[0]);
85 protected void onPreExecute() {
87 MainActivity context = getContext();
88 if (context == null) return;
89 context.onRetrieveStart();
92 protected void onPostExecute(Void aVoid) {
93 super.onPostExecute(aVoid);
94 MainActivity context = getContext();
95 if (context == null) return;
96 context.onRetrieveDone(success);
99 protected void onCancelled() {
101 MainActivity context = getContext();
102 if (context == null) return;
103 context.onRetrieveDone(false);
105 @SuppressLint("DefaultLocale")
107 protected Void doInBackground(Void... params) {
108 MobileLedgerProfile profile = Data.profile.get();
109 Progress progress = new Progress();
110 int maxTransactionId = Progress.INDETERMINATE;
112 ArrayList<LedgerAccount> accountList = new ArrayList<>();
113 ArrayList<LedgerTransaction> transactionList = new ArrayList<>();
114 HashMap<String, Void> accountNames = new HashMap<>();
115 LedgerAccount lastAccount = null;
116 Data.backgroundTaskCount.incrementAndGet();
118 HttpURLConnection http = NetworkUtil.prepare_connection("journal");
119 http.setAllowUserInteraction(false);
120 publishProgress(progress);
121 MainActivity ctx = getContext();
122 if (ctx == null) return null;
123 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
124 try (InputStream resp = http.getInputStream()) {
125 if (http.getResponseCode() != 200) throw new IOException(
126 String.format("HTTP error %d", http.getResponseCode()));
127 db.beginTransaction();
129 db.execSQL("UPDATE transactions set keep=0");
130 db.execSQL("update account_values set keep=0;");
131 db.execSQL("update accounts set keep=0;");
133 ParserState state = ParserState.EXPECTING_ACCOUNT;
136 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
138 int processedTransactionCount = 0;
139 int transactionId = 0;
140 int matchedTransactionsCount = 0;
141 LedgerTransaction transaction = null;
143 while ((line = buf.readLine()) != null) {
146 m = commentPattern.matcher(line);
148 // TODO: comments are ignored for now
149 Log.v("transaction-parser", "Ignoring comment");
152 //L(String.format("State is %d", updating));
154 case EXPECTING_ACCOUNT:
155 if (line.equals("<h2>General Journal</h2>")) {
156 state = ParserState.EXPECTING_TRANSACTION;
157 L("→ expecting transaction");
158 Data.accounts.set(accountList);
161 m = account_name_re.matcher(line);
163 String acct_encoded = m.group(1);
164 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
165 acct_name = acct_name.replace("\"", "");
166 L(String.format("found account: %s", acct_name));
168 profile.storeAccount(acct_name);
169 lastAccount = new LedgerAccount(acct_name);
171 // make sure the parent account(s) are present,
172 // synthesising them if necessary
173 String parentName = lastAccount.getParentName();
174 if (parentName != null) {
175 Stack<String> toAppend = new Stack<>();
176 while (parentName != null) {
177 if (accountNames.containsKey(parentName)) break;
178 toAppend.push(parentName);
179 parentName = new LedgerAccount(parentName)
182 while (!toAppend.isEmpty()) {
183 String aName = toAppend.pop();
184 LedgerAccount acc = new LedgerAccount(aName);
185 accountList.add(acc);
186 L(String.format("gap-filling with %s", aName));
187 accountNames.put(aName, null);
188 profile.storeAccount(aName);
192 accountList.add(lastAccount);
193 accountNames.put(acct_name, null);
195 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
196 L("→ expecting account amount");
200 case EXPECTING_ACCOUNT_AMOUNT:
201 m = account_value_re.matcher(line);
202 boolean match_found = false;
207 String value = m.group(1);
208 String currency = m.group(2);
209 if (currency == null) currency = "";
210 value = value.replace(',', '.');
211 L("curr=" + currency + ", value=" + value);
212 profile.storeAccountValue(lastAccount.getName(), currency,
213 Float.valueOf(value));
214 lastAccount.addAmount(Float.parseFloat(value), currency);
218 state = ParserState.EXPECTING_ACCOUNT;
219 L("→ expecting account");
224 case EXPECTING_TRANSACTION:
225 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
226 m = transactionStartPattern.matcher(line);
228 transactionId = Integer.valueOf(m.group(1));
229 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
231 "found transaction %d → expecting description",
233 progress.setProgress(++processedTransactionCount);
234 if (maxTransactionId < transactionId)
235 maxTransactionId = transactionId;
236 if ((progress.getTotal() == Progress.INDETERMINATE) ||
237 (progress.getTotal() < transactionId))
238 progress.setTotal(transactionId);
239 publishProgress(progress);
241 m = endPattern.matcher(line);
243 L("--- transaction value complete ---");
249 case EXPECTING_TRANSACTION_DESCRIPTION:
250 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
251 m = transactionDescriptionPattern.matcher(line);
253 if (transactionId == 0)
254 throw new TransactionParserException(
255 "Transaction Id is 0 while expecting " +
259 new LedgerTransaction(transactionId, m.group(1),
261 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
262 L(String.format("transaction %d created for %s (%s) →" +
263 " expecting details", transactionId,
264 m.group(1), m.group(2)));
268 case EXPECTING_TRANSACTION_DETAILS:
269 if (line.isEmpty()) {
270 // transaction data collected
271 if (transaction.existsInDb(db)) {
272 db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
273 "profile = ? and id=?",
274 new Object[]{profile.getUuid(),
277 matchedTransactionsCount++;
279 if (matchedTransactionsCount ==
280 MATCHING_TRANSACTIONS_LIMIT)
282 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
283 "profile = ? and id < ?",
284 new Object[]{profile.getUuid(),
288 progress.setTotal(progress.getProgress());
289 publishProgress(progress);
294 profile.storeTransaction(transaction);
295 matchedTransactionsCount = 0;
296 progress.setTotal(maxTransactionId);
299 state = ParserState.EXPECTING_TRANSACTION;
301 "transaction %s saved → expecting transaction",
302 transaction.getId()));
303 transaction.finishLoading();
304 transactionList.add(transaction);
306 // sounds like a good idea, but transaction-1 may not be the first one chronologically
307 // for example, when you add the initial seeding transaction after entering some others
308 // if (transactionId == 1) {
309 // L("This was the initial transaction. Terminating " +
315 m = transactionDetailsPattern.matcher(line);
317 String acc_name = m.group(1);
318 String amount = m.group(2);
319 String currency = m.group(3);
320 if (currency == null) currency = "";
321 amount = amount.replace(',', '.');
322 transaction.addAccount(
323 new LedgerTransactionAccount(acc_name,
324 Float.valueOf(amount), currency));
325 L(String.format("%d: %s = %s", transaction.getId(),
328 else throw new IllegalStateException(String.format(
329 "Can't parse transaction %d " + "details: %s",
330 transactionId, line));
334 throw new RuntimeException(
335 String.format("Unknown parser updating %s",
342 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
343 new String[]{profile.getUuid()});
344 db.setTransactionSuccessful();
346 Log.d("db", "Updating transaction value stamp");
347 Date now = new Date();
348 profile.set_option_value(MLDB.OPT_LAST_SCRAPE, now.getTime());
349 Data.lastUpdateDate.set(now);
350 Data.transactions.set(transactionList);
358 catch (MalformedURLException e) {
359 error = R.string.err_bad_backend_url;
362 catch (FileNotFoundException e) {
363 error = R.string.err_bad_auth;
366 catch (IOException e) {
367 error = R.string.err_net_io_error;
370 catch (OperationCanceledException e) {
371 error = R.string.err_cancelled;
375 Data.backgroundTaskCount.decrementAndGet();
379 private MainActivity getContext() {
380 return contextRef.get();
382 private void throwIfCancelled() {
383 if (isCancelled()) throw new OperationCanceledException(null);
386 private enum ParserState {
387 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
388 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
391 public class Progress {
392 public static final int INDETERMINATE = -1;
393 private int progress;
396 this(INDETERMINATE, INDETERMINATE);
398 Progress(int progress, int total) {
399 this.progress = progress;
402 public int getProgress() {
405 protected void setProgress(int progress) {
406 this.progress = progress;
408 public int getTotal() {
411 protected void setTotal(int total) {
416 private class TransactionParserException extends IllegalStateException {
417 TransactionParserException(String message) {