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 addAccount(db, 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);
185 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
186 new Object[]{lastAccount.getName(), currency,
189 lastAccount.addAmount(Float.parseFloat(value), currency);
193 state = ParserState.EXPECTING_ACCOUNT;
194 L("→ expecting account");
199 case EXPECTING_TRANSACTION:
200 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
201 m = transactionStartPattern.matcher(line);
203 transactionId = Integer.valueOf(m.group(1));
204 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
206 "found transaction %d → expecting description",
208 progress.setProgress(++processedTransactionCount);
209 if (maxTransactionId < transactionId)
210 maxTransactionId = transactionId;
211 if ((progress.getTotal() == Progress.INDETERMINATE) ||
212 (progress.getTotal() < transactionId))
213 progress.setTotal(transactionId);
214 publishProgress(progress);
216 m = endPattern.matcher(line);
218 L("--- transaction value complete ---");
224 case EXPECTING_TRANSACTION_DESCRIPTION:
225 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
226 m = transactionDescriptionPattern.matcher(line);
228 if (transactionId == 0)
229 throw new TransactionParserException(
230 "Transaction Id is 0 while expecting " +
234 new LedgerTransaction(transactionId, m.group(1),
236 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
237 L(String.format("transaction %d created for %s (%s) →" +
238 " expecting details", transactionId,
239 m.group(1), m.group(2)));
243 case EXPECTING_TRANSACTION_DETAILS:
244 if (line.isEmpty()) {
245 // transaction data collected
246 if (transaction.existsInDb(db)) {
247 db.execSQL("UPDATE transactions SET keep = 1 WHERE id" +
248 "=?", new Integer[]{transaction.getId()});
249 matchedTransactionsCount++;
251 if (matchedTransactionsCount ==
252 MATCHING_TRANSACTIONS_LIMIT)
254 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
256 new Integer[]{transaction.getId()});
258 progress.setTotal(progress.getProgress());
259 publishProgress(progress);
264 db.execSQL("DELETE from transactions WHERE id=?",
265 new Integer[]{transaction.getId()});
266 db.execSQL("DELETE from transaction_accounts WHERE " +
268 new Integer[]{transaction.getId()});
269 transaction.insertInto(db);
270 matchedTransactionsCount = 0;
271 progress.setTotal(maxTransactionId);
274 state = ParserState.EXPECTING_TRANSACTION;
276 "transaction %s saved → expecting transaction",
277 transaction.getId()));
278 transactionList.add(transaction);
280 // sounds like a good idea, but transaction-1 may not be the first one chronologically
281 // for example, when you add the initial seeding transaction after entering some others
282 // if (transactionId == 1) {
283 // L("This was the initial transaction. Terminating " +
289 m = transactionDetailsPattern.matcher(line);
291 String acc_name = m.group(1);
292 String amount = m.group(2);
293 String currency = m.group(3);
294 amount = amount.replace(',', '.');
295 transaction.addAccount(
296 new LedgerTransactionAccount(acc_name,
297 Float.valueOf(amount), currency));
298 L(String.format("%s = %s", acc_name, amount));
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 keep = 0");
315 db.setTransactionSuccessful();
317 Log.d("db", "Updating transaction value stamp");
318 Date now = new Date();
319 MLDB.set_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, now.getTime());
320 Data.lastUpdateDate.set(now);
321 Data.transactions.set(transactionList);
329 catch (MalformedURLException e) {
330 error = R.string.err_bad_backend_url;
333 catch (FileNotFoundException e) {
334 error = R.string.err_bad_auth;
337 catch (IOException e) {
338 error = R.string.err_net_io_error;
341 catch (OperationCanceledException e) {
342 error = R.string.err_cancelled;
346 Data.backgroundTaskCount.decrementAndGet();
350 private MainActivity getContext() {
351 return contextRef.get();
353 private void addAccount(SQLiteDatabase db, String name) {
355 LedgerAccount acc = new LedgerAccount(name);
356 db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
357 new Object[]{acc.getLevel(), name});
358 db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
359 "?,? " + "where (select changes() = 0)",
360 new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
361 name = acc.getParentName();
362 } while (name != null);
364 private void throwIfCancelled() {
365 if (isCancelled()) throw new OperationCanceledException(null);
368 private enum ParserState {
369 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
370 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
373 public class Progress {
374 public static final int INDETERMINATE = -1;
375 private int progress;
378 this(INDETERMINATE, INDETERMINATE);
380 Progress(int progress, int total) {
381 this.progress = progress;
384 public int getProgress() {
387 protected void setProgress(int progress) {
388 this.progress = progress;
390 public int getTotal() {
393 protected void setTotal(int total) {
398 private class TransactionParserException extends IllegalStateException {
399 TransactionParserException(String message) {