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.content.SharedPreferences;
22 import android.database.sqlite.SQLiteDatabase;
23 import android.os.AsyncTask;
24 import android.os.OperationCanceledException;
25 import android.util.Log;
27 import net.ktnx.mobileledger.R;
28 import net.ktnx.mobileledger.model.Data;
29 import net.ktnx.mobileledger.model.LedgerAccount;
30 import net.ktnx.mobileledger.model.LedgerTransaction;
31 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
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.regex.Matcher;
48 import java.util.regex.Pattern;
51 public class RetrieveTransactionsTask extends
52 AsyncTask<RetrieveTransactionsTask.Params, RetrieveTransactionsTask.Progress, Void> {
53 public static final int MATCHING_TRANSACTIONS_LIMIT = 50;
54 private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
55 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\\\"]*>([\\d.-]+)</td>");
56 private static final Pattern transactionDescriptionPattern =
57 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
58 private static final Pattern transactionDetailsPattern =
59 Pattern.compile("^\\s+" + "(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
60 private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
61 protected WeakReference<MainActivity> contextRef;
64 private Pattern ledger_title_re = Pattern.compile("<h1>([^<]+)</h1>");
65 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
66 Pattern account_value_re = Pattern.compile(
67 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
68 Pattern tr_end_re = Pattern.compile("</tr>");
69 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
70 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
71 private boolean success;
72 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
73 this.contextRef = contextRef;
75 private static final void L(String msg) {
76 Log.d("transaction-parser", msg);
79 protected void onProgressUpdate(Progress... values) {
80 super.onProgressUpdate(values);
81 MainActivity context = getContext();
82 if (context == null) return;
83 context.onRetrieveProgress(values[0]);
86 protected void onPreExecute() {
88 MainActivity context = getContext();
89 if (context == null) return;
90 context.onRetrieveStart();
93 protected void onPostExecute(Void aVoid) {
94 super.onPostExecute(aVoid);
95 MainActivity context = getContext();
96 if (context == null) return;
97 context.onRetrieveDone(success);
100 protected void onCancelled() {
102 MainActivity context = getContext();
103 if (context == null) return;
104 context.onRetrieveDone(false);
106 @SuppressLint("DefaultLocale")
108 protected Void doInBackground(Params... params) {
109 Progress progress = new Progress();
110 int maxTransactionId = Progress.INDETERMINATE;
112 ArrayList<LedgerAccount> accountList = new ArrayList<>();
113 ArrayList<LedgerTransaction> transactionList = new ArrayList<>();
114 LedgerAccount lastAccount = null;
115 Data.backgroundTaskCount.incrementAndGet();
117 HttpURLConnection http =
118 NetworkUtil.prepare_connection(params[0].getBackendPref(), "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 String ledgerTitle = null;
131 db.execSQL("UPDATE transactions set keep=0");
132 db.execSQL("update account_values set keep=0;");
133 db.execSQL("update accounts set keep=0;");
135 ParserState state = ParserState.EXPECTING_ACCOUNT;
138 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
140 int processedTransactionCount = 0;
141 int transactionId = 0;
142 int matchedTransactionsCount = 0;
143 LedgerTransaction transaction = null;
145 while ((line = buf.readLine()) != null) {
148 //L(String.format("State is %d", updating));
150 case EXPECTING_ACCOUNT:
151 if (line.equals("<h2>General Journal</h2>")) {
152 state = ParserState.EXPECTING_TRANSACTION;
153 L("→ expecting transaction");
154 Data.accounts.set(accountList);
157 m = account_name_re.matcher(line);
159 String acct_encoded = m.group(1);
160 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
161 acct_name = acct_name.replace("\"", "");
162 L(String.format("found account: %s", acct_name));
164 addAccount(db, acct_name);
165 lastAccount = new LedgerAccount(acct_name);
166 accountList.add(lastAccount);
168 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
169 L("→ expecting account amount");
171 else if (ledgerTitle == null) {
172 m = ledger_title_re.matcher(line);
174 ledgerTitle = m.group(1);
175 Data.ledgerTitle.set(ledgerTitle);
180 case EXPECTING_ACCOUNT_AMOUNT:
181 m = account_value_re.matcher(line);
182 boolean match_found = false;
187 String value = m.group(1);
188 String currency = m.group(2);
189 if (currency == null) currency = "";
190 value = value.replace(',', '.');
191 L("curr=" + currency + ", value=" + value);
193 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
194 new Object[]{lastAccount.getName(), currency,
197 lastAccount.addAmount(Float.parseFloat(value), currency);
201 state = ParserState.EXPECTING_ACCOUNT;
202 L("→ expecting account");
207 case EXPECTING_TRANSACTION:
208 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
209 m = transactionStartPattern.matcher(line);
211 transactionId = Integer.valueOf(m.group(1));
212 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
214 "found transaction %d → expecting description",
216 progress.setProgress(++processedTransactionCount);
217 if (maxTransactionId < transactionId)
218 maxTransactionId = transactionId;
219 if ((progress.getTotal() == Progress.INDETERMINATE) ||
220 (progress.getTotal() < transactionId))
221 progress.setTotal(transactionId);
222 publishProgress(progress);
224 m = endPattern.matcher(line);
226 L("--- transaction value complete ---");
232 case EXPECTING_TRANSACTION_DESCRIPTION:
233 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
234 m = transactionDescriptionPattern.matcher(line);
236 if (transactionId == 0)
237 throw new TransactionParserException(
238 "Transaction Id is 0 while expecting " +
242 new LedgerTransaction(transactionId, m.group(1),
244 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
245 L(String.format("transaction %d created for %s (%s) →" +
246 " expecting details", transactionId,
247 m.group(1), m.group(2)));
251 case EXPECTING_TRANSACTION_DETAILS:
252 if (line.isEmpty()) {
253 // transaction data collected
254 if (transaction.existsInDb(db)) {
255 db.execSQL("UPDATE transactions SET keep = 1 WHERE id" +
256 "=?", new Integer[]{transaction.getId()});
257 matchedTransactionsCount++;
259 if (matchedTransactionsCount ==
260 MATCHING_TRANSACTIONS_LIMIT)
262 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
264 new Integer[]{transaction.getId()});
266 progress.setTotal(progress.getProgress());
267 publishProgress(progress);
272 db.execSQL("DELETE from transactions WHERE id=?",
273 new Integer[]{transaction.getId()});
274 db.execSQL("DELETE from transaction_accounts WHERE " +
276 new Integer[]{transaction.getId()});
277 transaction.insertInto(db);
278 matchedTransactionsCount = 0;
279 progress.setTotal(maxTransactionId);
282 state = ParserState.EXPECTING_TRANSACTION;
284 "transaction %s saved → expecting transaction",
285 transaction.getId()));
286 transactionList.add(transaction);
288 // sounds like a good idea, but transaction-1 may not be the first one chronologically
289 // for example, when you add the initial seeding transaction after entering some others
290 // if (transactionId == 1) {
291 // L("This was the initial transaction. Terminating " +
297 m = transactionDetailsPattern.matcher(line);
299 String acc_name = m.group(1);
300 String amount = m.group(2);
301 String currency = m.group(3);
302 amount = amount.replace(',', '.');
303 transaction.addAccount(
304 new LedgerTransactionAccount(acc_name,
305 Float.valueOf(amount), currency));
306 L(String.format("%s = %s", acc_name, amount));
308 else throw new IllegalStateException(
309 String.format("Can't parse transaction %d details",
314 throw new RuntimeException(
315 String.format("Unknown parser updating %s",
322 db.execSQL("DELETE FROM transactions WHERE keep = 0");
323 db.setTransactionSuccessful();
325 Log.d("db", "Updating transaction value stamp");
326 Date now = new Date();
327 MLDB.set_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, now.getTime());
328 Data.lastUpdateDate.set(now);
329 Data.transactions.set(transactionList);
337 catch (MalformedURLException e) {
338 error = R.string.err_bad_backend_url;
341 catch (FileNotFoundException e) {
342 error = R.string.err_bad_auth;
345 catch (IOException e) {
346 error = R.string.err_net_io_error;
349 catch (OperationCanceledException e) {
350 error = R.string.err_cancelled;
354 Data.backgroundTaskCount.decrementAndGet();
358 private MainActivity getContext() {
359 return contextRef.get();
361 private void addAccount(SQLiteDatabase db, String name) {
363 LedgerAccount acc = new LedgerAccount(name);
364 db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
365 new Object[]{acc.getLevel(), name});
366 db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
367 "?,? " + "where (select changes() = 0)",
368 new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
369 name = acc.getParentName();
370 } while (name != null);
372 private void throwIfCancelled() {
373 if (isCancelled()) throw new OperationCanceledException(null);
376 private enum ParserState {
377 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
378 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
381 public static class Params {
382 private SharedPreferences backendPref;
384 public Params(SharedPreferences backendPref) {
385 this.backendPref = backendPref;
387 SharedPreferences getBackendPref() {
392 public class Progress {
393 public static final int INDETERMINATE = -1;
394 private int progress;
397 this(INDETERMINATE, INDETERMINATE);
399 Progress(int progress, int total) {
400 this.progress = progress;
403 public int getProgress() {
406 protected void setProgress(int progress) {
407 this.progress = progress;
409 public int getTotal() {
412 protected void setTotal(int total) {
417 private class TransactionParserException extends IllegalStateException {
418 TransactionParserException(String message) {