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 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;
63 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
64 Pattern account_value_re = Pattern.compile(
65 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
66 Pattern tr_end_re = Pattern.compile("</tr>");
67 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
68 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
70 private boolean success;
71 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
72 this.contextRef = contextRef;
74 private static final 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 LedgerAccount lastAccount = null;
115 Data.backgroundTaskCount.incrementAndGet();
117 HttpURLConnection http = NetworkUtil.prepare_connection("journal");
118 http.setAllowUserInteraction(false);
119 publishProgress(progress);
120 MainActivity ctx = getContext();
121 if (ctx == null) return null;
122 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
123 try (InputStream resp = http.getInputStream()) {
124 if (http.getResponseCode() != 200) throw new IOException(
125 String.format("HTTP error %d", http.getResponseCode()));
126 db.beginTransaction();
128 String ledgerTitle = null;
130 db.execSQL("UPDATE transactions set keep=0");
131 db.execSQL("update account_values set keep=0;");
132 db.execSQL("update accounts set keep=0;");
134 ParserState state = ParserState.EXPECTING_ACCOUNT;
137 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
139 int processedTransactionCount = 0;
140 int transactionId = 0;
141 int matchedTransactionsCount = 0;
142 LedgerTransaction transaction = null;
144 while ((line = buf.readLine()) != null) {
147 //L(String.format("State is %d", updating));
149 case EXPECTING_ACCOUNT:
150 if (line.equals("<h2>General Journal</h2>")) {
151 state = ParserState.EXPECTING_TRANSACTION;
152 L("→ expecting transaction");
153 Data.accounts.set(accountList);
156 m = account_name_re.matcher(line);
158 String acct_encoded = m.group(1);
159 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
160 acct_name = acct_name.replace("\"", "");
161 L(String.format("found account: %s", acct_name));
163 profile.storeAccount(acct_name);
164 lastAccount = new LedgerAccount(acct_name);
165 accountList.add(lastAccount);
167 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
168 L("→ expecting account amount");
172 case EXPECTING_ACCOUNT_AMOUNT:
173 m = account_value_re.matcher(line);
174 boolean match_found = false;
179 String value = m.group(1);
180 String currency = m.group(2);
181 if (currency == null) currency = "";
182 value = value.replace(',', '.');
183 L("curr=" + currency + ", value=" + value);
184 profile.storeAccountValue(lastAccount.getName(), currency,
185 Float.valueOf(value));
186 lastAccount.addAmount(Float.parseFloat(value), currency);
190 state = ParserState.EXPECTING_ACCOUNT;
191 L("→ expecting account");
196 case EXPECTING_TRANSACTION:
197 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
198 m = transactionStartPattern.matcher(line);
200 transactionId = Integer.valueOf(m.group(1));
201 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
203 "found transaction %d → expecting description",
205 progress.setProgress(++processedTransactionCount);
206 if (maxTransactionId < transactionId)
207 maxTransactionId = transactionId;
208 if ((progress.getTotal() == Progress.INDETERMINATE) ||
209 (progress.getTotal() < transactionId))
210 progress.setTotal(transactionId);
211 publishProgress(progress);
213 m = endPattern.matcher(line);
215 L("--- transaction value complete ---");
221 case EXPECTING_TRANSACTION_DESCRIPTION:
222 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
223 m = transactionDescriptionPattern.matcher(line);
225 if (transactionId == 0)
226 throw new TransactionParserException(
227 "Transaction Id is 0 while expecting " +
231 new LedgerTransaction(transactionId, m.group(1),
233 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
234 L(String.format("transaction %d created for %s (%s) →" +
235 " expecting details", transactionId,
236 m.group(1), m.group(2)));
240 case EXPECTING_TRANSACTION_DETAILS:
241 if (line.isEmpty()) {
242 // transaction data collected
243 if (transaction.existsInDb(db)) {
244 db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
245 "profile = ? and id=?",
246 new Object[]{profile.getUuid(),
249 matchedTransactionsCount++;
251 if (matchedTransactionsCount ==
252 MATCHING_TRANSACTIONS_LIMIT)
254 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
255 "profile = ? and id < ?",
256 new Object[]{profile.getUuid(),
260 progress.setTotal(progress.getProgress());
261 publishProgress(progress);
266 profile.storeTransaction(transaction);
267 matchedTransactionsCount = 0;
268 progress.setTotal(maxTransactionId);
271 state = ParserState.EXPECTING_TRANSACTION;
273 "transaction %s saved → expecting transaction",
274 transaction.getId()));
275 transaction.finishLoading();
276 transactionList.add(transaction);
278 // sounds like a good idea, but transaction-1 may not be the first one chronologically
279 // for example, when you add the initial seeding transaction after entering some others
280 // if (transactionId == 1) {
281 // L("This was the initial transaction. Terminating " +
287 m = transactionDetailsPattern.matcher(line);
289 String acc_name = m.group(1);
290 String amount = m.group(2);
291 String currency = m.group(3);
292 if (currency == null) currency = "";
293 amount = amount.replace(',', '.');
294 transaction.addAccount(
295 new LedgerTransactionAccount(acc_name,
296 Float.valueOf(amount), currency));
297 L(String.format("%d: %s = %s", transaction.getId(),
300 else throw new IllegalStateException(
301 String.format("Can't parse transaction %d details",
306 throw new RuntimeException(
307 String.format("Unknown parser updating %s",
314 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
315 new String[]{profile.getUuid()});
316 db.setTransactionSuccessful();
318 Log.d("db", "Updating transaction value stamp");
319 Date now = new Date();
320 profile.set_option_value(MLDB.OPT_LAST_SCRAPE, now.getTime());
321 Data.lastUpdateDate.set(now);
322 Data.transactions.set(transactionList);
330 catch (MalformedURLException e) {
331 error = R.string.err_bad_backend_url;
334 catch (FileNotFoundException e) {
335 error = R.string.err_bad_auth;
338 catch (IOException e) {
339 error = R.string.err_net_io_error;
342 catch (OperationCanceledException e) {
343 error = R.string.err_cancelled;
347 Data.backgroundTaskCount.decrementAndGet();
351 private MainActivity getContext() {
352 return contextRef.get();
354 private void throwIfCancelled() {
355 if (isCancelled()) throw new OperationCanceledException(null);
358 private enum ParserState {
359 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
360 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
363 public class Progress {
364 public static final int INDETERMINATE = -1;
365 private int progress;
368 this(INDETERMINATE, INDETERMINATE);
370 Progress(int progress, int total) {
371 this.progress = progress;
374 public int getProgress() {
377 protected void setProgress(int progress) {
378 this.progress = progress;
380 public int getTotal() {
383 protected void setTotal(int total) {
388 private class TransactionParserException extends IllegalStateException {
389 TransactionParserException(String message) {