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.regex.Matcher;
48 import java.util.regex.Pattern;
51 public class RetrieveTransactionsTask
52 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, Void> {
53 public static final int MATCHING_TRANSACTIONS_LIMIT = 50;
54 public static final Pattern commentPattern = Pattern.compile("^\\s*;");
55 private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
56 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
57 private static final Pattern transactionDescriptionPattern =
58 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
59 private static final Pattern transactionDetailsPattern =
60 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
61 private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
62 protected WeakReference<MainActivity> contextRef;
64 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
65 Pattern account_value_re = Pattern.compile(
66 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
67 Pattern tr_end_re = Pattern.compile("</tr>");
68 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
69 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(Void... params) {
109 MobileLedgerProfile profile = Data.profile.get();
110 Progress progress = new Progress();
111 int maxTransactionId = Progress.INDETERMINATE;
113 ArrayList<LedgerAccount> accountList = new ArrayList<>();
114 ArrayList<LedgerTransaction> transactionList = new ArrayList<>();
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 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 m = commentPattern.matcher(line);
150 // TODO: comments are ignored for now
151 Log.v("transaction-parser", "Ignoring comment");
154 //L(String.format("State is %d", updating));
156 case EXPECTING_ACCOUNT:
157 if (line.equals("<h2>General Journal</h2>")) {
158 state = ParserState.EXPECTING_TRANSACTION;
159 L("→ expecting transaction");
160 Data.accounts.set(accountList);
163 m = account_name_re.matcher(line);
165 String acct_encoded = m.group(1);
166 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
167 acct_name = acct_name.replace("\"", "");
168 L(String.format("found account: %s", acct_name));
170 profile.storeAccount(acct_name);
171 lastAccount = new LedgerAccount(acct_name);
172 accountList.add(lastAccount);
174 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
175 L("→ expecting account amount");
179 case EXPECTING_ACCOUNT_AMOUNT:
180 m = account_value_re.matcher(line);
181 boolean match_found = false;
186 String value = m.group(1);
187 String currency = m.group(2);
188 if (currency == null) currency = "";
189 value = value.replace(',', '.');
190 L("curr=" + currency + ", value=" + value);
191 profile.storeAccountValue(lastAccount.getName(), currency,
192 Float.valueOf(value));
193 lastAccount.addAmount(Float.parseFloat(value), currency);
197 state = ParserState.EXPECTING_ACCOUNT;
198 L("→ expecting account");
203 case EXPECTING_TRANSACTION:
204 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
205 m = transactionStartPattern.matcher(line);
207 transactionId = Integer.valueOf(m.group(1));
208 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
210 "found transaction %d → expecting description",
212 progress.setProgress(++processedTransactionCount);
213 if (maxTransactionId < transactionId)
214 maxTransactionId = transactionId;
215 if ((progress.getTotal() == Progress.INDETERMINATE) ||
216 (progress.getTotal() < transactionId))
217 progress.setTotal(transactionId);
218 publishProgress(progress);
220 m = endPattern.matcher(line);
222 L("--- transaction value complete ---");
228 case EXPECTING_TRANSACTION_DESCRIPTION:
229 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
230 m = transactionDescriptionPattern.matcher(line);
232 if (transactionId == 0)
233 throw new TransactionParserException(
234 "Transaction Id is 0 while expecting " +
238 new LedgerTransaction(transactionId, m.group(1),
240 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
241 L(String.format("transaction %d created for %s (%s) →" +
242 " expecting details", transactionId,
243 m.group(1), m.group(2)));
247 case EXPECTING_TRANSACTION_DETAILS:
248 if (line.isEmpty()) {
249 // transaction data collected
250 if (transaction.existsInDb(db)) {
251 db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
252 "profile = ? and id=?",
253 new Object[]{profile.getUuid(),
256 matchedTransactionsCount++;
258 if (matchedTransactionsCount ==
259 MATCHING_TRANSACTIONS_LIMIT)
261 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
262 "profile = ? and id < ?",
263 new Object[]{profile.getUuid(),
267 progress.setTotal(progress.getProgress());
268 publishProgress(progress);
273 profile.storeTransaction(transaction);
274 matchedTransactionsCount = 0;
275 progress.setTotal(maxTransactionId);
278 state = ParserState.EXPECTING_TRANSACTION;
280 "transaction %s saved → expecting transaction",
281 transaction.getId()));
282 transaction.finishLoading();
283 transactionList.add(transaction);
285 // sounds like a good idea, but transaction-1 may not be the first one chronologically
286 // for example, when you add the initial seeding transaction after entering some others
287 // if (transactionId == 1) {
288 // L("This was the initial transaction. Terminating " +
294 m = transactionDetailsPattern.matcher(line);
296 String acc_name = m.group(1);
297 String amount = m.group(2);
298 String currency = m.group(3);
299 if (currency == null) currency = "";
300 amount = amount.replace(',', '.');
301 transaction.addAccount(
302 new LedgerTransactionAccount(acc_name,
303 Float.valueOf(amount), currency));
304 L(String.format("%d: %s = %s", transaction.getId(),
307 else throw new IllegalStateException(String.format(
308 "Can't parse transaction %d " + "details: %s",
309 transactionId, line));
313 throw new RuntimeException(
314 String.format("Unknown parser updating %s",
321 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
322 new String[]{profile.getUuid()});
323 db.setTransactionSuccessful();
325 Log.d("db", "Updating transaction value stamp");
326 Date now = new Date();
327 profile.set_option_value(MLDB.OPT_LAST_SCRAPE, 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 throwIfCancelled() {
362 if (isCancelled()) throw new OperationCanceledException(null);
365 private enum ParserState {
366 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
367 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
370 public class Progress {
371 public static final int INDETERMINATE = -1;
372 private int progress;
375 this(INDETERMINATE, INDETERMINATE);
377 Progress(int progress, int total) {
378 this.progress = progress;
381 public int getProgress() {
384 protected void setProgress(int progress) {
385 this.progress = progress;
387 public int getTotal() {
390 protected void setTotal(int total) {
395 private class TransactionParserException extends IllegalStateException {
396 TransactionParserException(String message) {