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.ui.transaction_list.TransactionListViewModel;
34 import net.ktnx.mobileledger.utils.MLDB;
35 import net.ktnx.mobileledger.utils.NetworkUtil;
37 import java.io.BufferedReader;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.io.InputStreamReader;
42 import java.lang.ref.WeakReference;
43 import java.net.HttpURLConnection;
44 import java.net.MalformedURLException;
45 import java.net.URLDecoder;
46 import java.util.ArrayList;
47 import java.util.Date;
48 import java.util.HashMap;
49 import java.util.Stack;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
54 public class RetrieveTransactionsTask
55 extends AsyncTask<Void, RetrieveTransactionsTask.Progress, Void> {
56 private static final int MATCHING_TRANSACTIONS_LIMIT = 50;
57 private static final Pattern reComment = Pattern.compile("^\\s*;");
58 private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
59 "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
60 private static final Pattern reTransactionDescription =
61 Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
62 private static final Pattern reTransactionDetails =
63 Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
64 private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
65 private WeakReference<MainActivity> contextRef;
68 private boolean success;
69 private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
70 private Pattern reAccountValue = Pattern.compile(
71 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
72 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
73 this.contextRef = contextRef;
75 private static 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 HashMap<String, Void> accountNames = new HashMap<>();
115 LedgerAccount lastAccount = null;
116 boolean onlyStarred = Data.optShowOnlyStarred.get();
117 Data.backgroundTaskCount.incrementAndGet();
119 HttpURLConnection http = NetworkUtil.prepareConnection("journal");
120 http.setAllowUserInteraction(false);
121 publishProgress(progress);
122 MainActivity ctx = getContext();
123 if (ctx == null) return null;
124 try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
125 try (InputStream resp = http.getInputStream()) {
126 if (http.getResponseCode() != 200) throw new IOException(
127 String.format("HTTP error %d", http.getResponseCode()));
128 db.beginTransaction();
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 m = reComment.matcher(line);
149 // TODO: comments are ignored for now
150 Log.v("transaction-parser", "Ignoring comment");
153 //L(String.format("State is %d", updating));
155 case EXPECTING_ACCOUNT:
156 if (line.equals("<h2>General Journal</h2>")) {
157 state = ParserState.EXPECTING_TRANSACTION;
158 L("→ expecting transaction");
159 Data.accounts.set(accountList);
162 m = reAccountName.matcher(line);
164 String acct_encoded = m.group(1);
165 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
166 acct_name = acct_name.replace("\"", "");
167 L(String.format("found account: %s", acct_name));
169 lastAccount = profile.loadAccount(acct_name);
170 if (lastAccount == null) {
171 lastAccount = new LedgerAccount(acct_name);
172 profile.storeAccount(lastAccount);
175 // make sure the parent account(s) are present,
176 // synthesising them if necessary
177 String parentName = lastAccount.getParentName();
178 if (parentName != null) {
179 Stack<String> toAppend = new Stack<>();
180 while (parentName != null) {
181 if (accountNames.containsKey(parentName)) break;
182 toAppend.push(parentName);
183 parentName = new LedgerAccount(parentName)
186 while (!toAppend.isEmpty()) {
187 String aName = toAppend.pop();
188 LedgerAccount acc = new LedgerAccount(aName);
189 acc.setHidden(lastAccount.isHidden());
190 if (!onlyStarred || !acc.isHidden())
191 accountList.add(acc);
192 L(String.format("gap-filling with %s", aName));
193 accountNames.put(aName, null);
194 profile.storeAccount(acc);
198 if (!onlyStarred || !lastAccount.isHidden())
199 accountList.add(lastAccount);
200 accountNames.put(acct_name, null);
202 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
203 L("→ expecting account amount");
207 case EXPECTING_ACCOUNT_AMOUNT:
208 m = reAccountValue.matcher(line);
209 boolean match_found = false;
214 String value = m.group(1);
215 String currency = m.group(2);
216 if (currency == null) currency = "";
217 value = value.replace(',', '.');
218 L("curr=" + currency + ", value=" + value);
219 profile.storeAccountValue(lastAccount.getName(), currency,
220 Float.valueOf(value));
221 lastAccount.addAmount(Float.parseFloat(value), currency);
225 state = ParserState.EXPECTING_ACCOUNT;
226 L("→ expecting account");
231 case EXPECTING_TRANSACTION:
232 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
233 m = reTransactionStart.matcher(line);
235 transactionId = Integer.valueOf(m.group(1));
236 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
238 "found transaction %d → expecting description",
240 progress.setProgress(++processedTransactionCount);
241 if (maxTransactionId < transactionId)
242 maxTransactionId = transactionId;
243 if ((progress.getTotal() == Progress.INDETERMINATE) ||
244 (progress.getTotal() < transactionId))
245 progress.setTotal(transactionId);
246 publishProgress(progress);
248 m = reEnd.matcher(line);
250 L("--- transaction value complete ---");
256 case EXPECTING_TRANSACTION_DESCRIPTION:
257 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
258 m = reTransactionDescription.matcher(line);
260 if (transactionId == 0)
261 throw new TransactionParserException(
262 "Transaction Id is 0 while expecting " +
266 new LedgerTransaction(transactionId, m.group(1),
268 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
269 L(String.format("transaction %d created for %s (%s) →" +
270 " expecting details", transactionId,
271 m.group(1), m.group(2)));
275 case EXPECTING_TRANSACTION_DETAILS:
276 if (line.isEmpty()) {
277 // transaction data collected
278 if (transaction.existsInDb(db)) {
279 db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
280 "profile = ? and id=?",
281 new Object[]{profile.getUuid(),
284 matchedTransactionsCount++;
286 if (matchedTransactionsCount ==
287 MATCHING_TRANSACTIONS_LIMIT)
289 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
290 "profile = ? and id < ?",
291 new Object[]{profile.getUuid(),
295 progress.setTotal(progress.getProgress());
296 publishProgress(progress);
301 profile.storeTransaction(transaction);
302 matchedTransactionsCount = 0;
303 progress.setTotal(maxTransactionId);
306 state = ParserState.EXPECTING_TRANSACTION;
308 "transaction %s saved → expecting transaction",
309 transaction.getId()));
310 transaction.finishLoading();
312 // sounds like a good idea, but transaction-1 may not be the first one chronologically
313 // for example, when you add the initial seeding transaction after entering some others
314 // if (transactionId == 1) {
315 // L("This was the initial transaction. Terminating " +
321 m = reTransactionDetails.matcher(line);
323 String acc_name = m.group(1);
324 String amount = m.group(2);
325 String currency = m.group(3);
326 if (currency == null) currency = "";
327 amount = amount.replace(',', '.');
328 transaction.addAccount(
329 new LedgerTransactionAccount(acc_name,
330 Float.valueOf(amount), currency));
331 L(String.format("%d: %s = %s", transaction.getId(),
334 else throw new IllegalStateException(String.format(
335 "Can't parse transaction %d " + "details: %s",
336 transactionId, line));
340 throw new RuntimeException(
341 String.format("Unknown parser updating %s",
348 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
349 new String[]{profile.getUuid()});
350 db.setTransactionSuccessful();
352 Log.d("db", "Updating transaction value stamp");
353 Date now = new Date();
354 profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
355 Data.lastUpdateDate.set(now);
356 TransactionListViewModel.scheduleTransactionListReload();
364 catch (MalformedURLException e) {
365 error = R.string.err_bad_backend_url;
368 catch (FileNotFoundException e) {
369 error = R.string.err_bad_auth;
372 catch (IOException e) {
373 error = R.string.err_net_io_error;
376 catch (OperationCanceledException e) {
377 error = R.string.err_cancelled;
381 Data.backgroundTaskCount.decrementAndGet();
385 private MainActivity getContext() {
386 return contextRef.get();
388 private void throwIfCancelled() {
389 if (isCancelled()) throw new OperationCanceledException(null);
392 private enum ParserState {
393 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
394 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
397 public class Progress {
398 public static final int INDETERMINATE = -1;
399 private int progress;
402 this(INDETERMINATE, INDETERMINATE);
404 Progress(int progress, int total) {
405 this.progress = progress;
408 public int getProgress() {
411 protected void setProgress(int progress) {
412 this.progress = progress;
414 public int getTotal() {
417 protected void setTotal(int total) {
422 private class TransactionParserException extends IllegalStateException {
423 TransactionParserException(String message) {