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 public static final int MATCHING_TRANSACTIONS_LIMIT = 50;
56 public 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 protected WeakReference<MainActivity> contextRef;
66 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
67 Pattern account_value_re = Pattern.compile(
68 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
69 Pattern tr_end_re = Pattern.compile("</tr>");
70 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
71 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
73 private boolean success;
74 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
75 this.contextRef = contextRef;
77 private static final void L(String msg) {
78 Log.d("transaction-parser", msg);
81 protected void onProgressUpdate(Progress... values) {
82 super.onProgressUpdate(values);
83 MainActivity context = getContext();
84 if (context == null) return;
85 context.onRetrieveProgress(values[0]);
88 protected void onPreExecute() {
90 MainActivity context = getContext();
91 if (context == null) return;
92 context.onRetrieveStart();
95 protected void onPostExecute(Void aVoid) {
96 super.onPostExecute(aVoid);
97 MainActivity context = getContext();
98 if (context == null) return;
99 context.onRetrieveDone(success);
102 protected void onCancelled() {
104 MainActivity context = getContext();
105 if (context == null) return;
106 context.onRetrieveDone(false);
108 @SuppressLint("DefaultLocale")
110 protected Void doInBackground(Void... params) {
111 MobileLedgerProfile profile = Data.profile.get();
112 Progress progress = new Progress();
113 int maxTransactionId = Progress.INDETERMINATE;
115 ArrayList<LedgerAccount> accountList = new ArrayList<>();
116 ArrayList<LedgerTransaction> transactionList = new ArrayList<>();
117 HashMap<String, Void> accountNames = new HashMap<>();
118 LedgerAccount lastAccount = null;
119 Data.backgroundTaskCount.incrementAndGet();
121 HttpURLConnection http = NetworkUtil.prepare_connection("journal");
122 http.setAllowUserInteraction(false);
123 publishProgress(progress);
124 MainActivity ctx = getContext();
125 if (ctx == null) return null;
126 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
127 try (InputStream resp = http.getInputStream()) {
128 if (http.getResponseCode() != 200) throw new IOException(
129 String.format("HTTP error %d", http.getResponseCode()));
130 db.beginTransaction();
132 String ledgerTitle = null;
134 db.execSQL("UPDATE transactions set keep=0");
135 db.execSQL("update account_values set keep=0;");
136 db.execSQL("update accounts set keep=0;");
138 ParserState state = ParserState.EXPECTING_ACCOUNT;
141 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
143 int processedTransactionCount = 0;
144 int transactionId = 0;
145 int matchedTransactionsCount = 0;
146 LedgerTransaction transaction = null;
148 while ((line = buf.readLine()) != null) {
151 m = commentPattern.matcher(line);
153 // TODO: comments are ignored for now
154 Log.v("transaction-parser", "Ignoring comment");
157 //L(String.format("State is %d", updating));
159 case EXPECTING_ACCOUNT:
160 if (line.equals("<h2>General Journal</h2>")) {
161 state = ParserState.EXPECTING_TRANSACTION;
162 L("→ expecting transaction");
163 Data.accounts.set(accountList);
166 m = account_name_re.matcher(line);
168 String acct_encoded = m.group(1);
169 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
170 acct_name = acct_name.replace("\"", "");
171 L(String.format("found account: %s", acct_name));
173 profile.storeAccount(acct_name);
174 lastAccount = new LedgerAccount(acct_name);
176 // make sure the parent account(s) are present,
177 // synthesising them if necessary
178 String parentName = lastAccount.getParentName();
179 if (parentName != null) {
180 Stack<String> toAppend = new Stack<>();
181 while (parentName != null) {
182 if (accountNames.containsKey(parentName)) break;
183 toAppend.push(parentName);
184 parentName = new LedgerAccount(parentName)
187 while (!toAppend.isEmpty()) {
188 String aName = toAppend.pop();
189 LedgerAccount acc = new LedgerAccount(aName);
190 accountList.add(acc);
191 L(String.format("gap-filling with %s", aName));
192 accountNames.put(aName, null);
193 profile.storeAccount(aName);
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 = account_value_re.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 = transactionStartPattern.matcher(line);
233 transactionId = Integer.valueOf(m.group(1));
234 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
236 "found transaction %d → expecting description",
238 progress.setProgress(++processedTransactionCount);
239 if (maxTransactionId < transactionId)
240 maxTransactionId = transactionId;
241 if ((progress.getTotal() == Progress.INDETERMINATE) ||
242 (progress.getTotal() < transactionId))
243 progress.setTotal(transactionId);
244 publishProgress(progress);
246 m = endPattern.matcher(line);
248 L("--- transaction value complete ---");
254 case EXPECTING_TRANSACTION_DESCRIPTION:
255 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
256 m = transactionDescriptionPattern.matcher(line);
258 if (transactionId == 0)
259 throw new TransactionParserException(
260 "Transaction Id is 0 while expecting " +
264 new LedgerTransaction(transactionId, m.group(1),
266 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
267 L(String.format("transaction %d created for %s (%s) →" +
268 " expecting details", transactionId,
269 m.group(1), m.group(2)));
273 case EXPECTING_TRANSACTION_DETAILS:
274 if (line.isEmpty()) {
275 // transaction data collected
276 if (transaction.existsInDb(db)) {
277 db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
278 "profile = ? and id=?",
279 new Object[]{profile.getUuid(),
282 matchedTransactionsCount++;
284 if (matchedTransactionsCount ==
285 MATCHING_TRANSACTIONS_LIMIT)
287 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
288 "profile = ? and id < ?",
289 new Object[]{profile.getUuid(),
293 progress.setTotal(progress.getProgress());
294 publishProgress(progress);
299 profile.storeTransaction(transaction);
300 matchedTransactionsCount = 0;
301 progress.setTotal(maxTransactionId);
304 state = ParserState.EXPECTING_TRANSACTION;
306 "transaction %s saved → expecting transaction",
307 transaction.getId()));
308 transaction.finishLoading();
309 transactionList.add(transaction);
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 = transactionDetailsPattern.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",
347 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
348 new String[]{profile.getUuid()});
349 db.setTransactionSuccessful();
351 Log.d("db", "Updating transaction value stamp");
352 Date now = new Date();
353 profile.set_option_value(MLDB.OPT_LAST_SCRAPE, now.getTime());
354 Data.lastUpdateDate.set(now);
355 Data.transactions.set(transactionList);
363 catch (MalformedURLException e) {
364 error = R.string.err_bad_backend_url;
367 catch (FileNotFoundException e) {
368 error = R.string.err_bad_auth;
371 catch (IOException e) {
372 error = R.string.err_net_io_error;
375 catch (OperationCanceledException e) {
376 error = R.string.err_cancelled;
380 Data.backgroundTaskCount.decrementAndGet();
384 private MainActivity getContext() {
385 return contextRef.get();
387 private void throwIfCancelled() {
388 if (isCancelled()) throw new OperationCanceledException(null);
391 private enum ParserState {
392 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
393 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
396 public class Progress {
397 public static final int INDETERMINATE = -1;
398 private int progress;
401 this(INDETERMINATE, INDETERMINATE);
403 Progress(int progress, int total) {
404 this.progress = progress;
407 public int getProgress() {
410 protected void setProgress(int progress) {
411 this.progress = progress;
413 public int getTotal() {
416 protected void setTotal(int total) {
421 private class TransactionParserException extends IllegalStateException {
422 TransactionParserException(String message) {