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.model.Data;
27 import net.ktnx.mobileledger.model.LedgerAccount;
28 import net.ktnx.mobileledger.model.LedgerTransaction;
29 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
30 import net.ktnx.mobileledger.model.MobileLedgerProfile;
31 import net.ktnx.mobileledger.ui.activity.MainActivity;
32 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
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.text.ParseException;
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, String> {
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 Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
69 private Pattern reAccountValue = Pattern.compile(
70 "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
71 public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
72 this.contextRef = contextRef;
74 private static 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(String error) {
93 super.onPostExecute(error);
94 MainActivity context = getContext();
95 if (context == null) return;
96 context.onRetrieveDone(error);
99 protected void onCancelled() {
101 MainActivity context = getContext();
102 if (context == null) return;
103 context.onRetrieveDone(null);
105 @SuppressLint("DefaultLocale")
107 protected String doInBackground(Void... params) {
108 MobileLedgerProfile profile = Data.profile.get();
109 Progress progress = new Progress();
110 int maxTransactionId = Progress.INDETERMINATE;
111 ArrayList<LedgerAccount> accountList = new ArrayList<>();
112 HashMap<String, Void> accountNames = new HashMap<>();
113 LedgerAccount lastAccount = null;
114 boolean onlyStarred = Data.optShowOnlyStarred.get();
115 Data.backgroundTaskCount.incrementAndGet();
117 HttpURLConnection http = NetworkUtil.prepareConnection("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 db.execSQL("UPDATE transactions set keep=0");
129 db.execSQL("update account_values set keep=0;");
130 db.execSQL("update accounts set keep=0;");
132 ParserState state = ParserState.EXPECTING_ACCOUNT;
135 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
137 int processedTransactionCount = 0;
138 int transactionId = 0;
139 int matchedTransactionsCount = 0;
140 LedgerTransaction transaction = null;
142 while ((line = buf.readLine()) != null) {
145 m = reComment.matcher(line);
147 // TODO: comments are ignored for now
148 Log.v("transaction-parser", "Ignoring comment");
151 //L(String.format("State is %d", updating));
153 case EXPECTING_ACCOUNT:
154 if (line.equals("<h2>General Journal</h2>")) {
155 state = ParserState.EXPECTING_TRANSACTION;
156 L("→ expecting transaction");
157 Data.accounts.set(accountList);
160 m = reAccountName.matcher(line);
162 String acct_encoded = m.group(1);
163 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
164 acct_name = acct_name.replace("\"", "");
165 L(String.format("found account: %s", acct_name));
167 lastAccount = profile.loadAccount(acct_name);
168 if (lastAccount == null) {
169 lastAccount = new LedgerAccount(acct_name);
170 profile.storeAccount(lastAccount);
173 // make sure the parent account(s) are present,
174 // synthesising them if necessary
175 String parentName = lastAccount.getParentName();
176 if (parentName != null) {
177 Stack<String> toAppend = new Stack<>();
178 while (parentName != null) {
179 if (accountNames.containsKey(parentName)) break;
180 toAppend.push(parentName);
181 parentName = new LedgerAccount(parentName)
184 while (!toAppend.isEmpty()) {
185 String aName = toAppend.pop();
186 LedgerAccount acc = new LedgerAccount(aName);
187 acc.setHidden(lastAccount.isHidden());
188 if (!onlyStarred || !acc.isHidden())
189 accountList.add(acc);
190 L(String.format("gap-filling with %s", aName));
191 accountNames.put(aName, null);
192 profile.storeAccount(acc);
196 if (!onlyStarred || !lastAccount.isHidden())
197 accountList.add(lastAccount);
198 accountNames.put(acct_name, null);
200 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
201 L("→ expecting account amount");
205 case EXPECTING_ACCOUNT_AMOUNT:
206 m = reAccountValue.matcher(line);
207 boolean match_found = false;
212 String value = m.group(1);
213 String currency = m.group(2);
214 if (currency == null) currency = "";
215 value = value.replace(',', '.');
216 L("curr=" + currency + ", value=" + value);
217 profile.storeAccountValue(lastAccount.getName(), currency,
218 Float.valueOf(value));
219 lastAccount.addAmount(Float.parseFloat(value), currency);
223 state = ParserState.EXPECTING_ACCOUNT;
224 L("→ expecting account");
229 case EXPECTING_TRANSACTION:
230 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
231 m = reTransactionStart.matcher(line);
233 transactionId = Integer.valueOf(m.group(1));
234 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
236 "found transaction %d → expecting description",
238 progress.setProgress(++processedTransactionCount);
239 if (maxTransactionId < transactionId)
240 maxTransactionId = transactionId;
241 if ((progress.getTotal() == Progress.INDETERMINATE) ||
242 (progress.getTotal() < transactionId))
243 progress.setTotal(transactionId);
244 publishProgress(progress);
246 m = reEnd.matcher(line);
248 L("--- transaction value complete ---");
253 case EXPECTING_TRANSACTION_DESCRIPTION:
254 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
255 m = reTransactionDescription.matcher(line);
257 if (transactionId == 0)
258 throw new TransactionParserException(
259 "Transaction Id is 0 while expecting " +
262 String date = m.group(1);
264 int equalsIndex = date.indexOf('=');
265 if (equalsIndex >= 0)
266 date = date.substring(equalsIndex + 1);
267 transaction = new LedgerTransaction(transactionId, date,
270 catch (ParseException e) {
272 return String.format("Error parsing date '%s'", date);
274 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
275 L(String.format("transaction %d created for %s (%s) →" +
276 " expecting details", transactionId, date,
281 case EXPECTING_TRANSACTION_DETAILS:
282 if (line.isEmpty()) {
283 // transaction data collected
284 if (transaction.existsInDb(db)) {
285 db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
286 "profile = ? and id=?",
287 new Object[]{profile.getUuid(),
290 matchedTransactionsCount++;
292 if (matchedTransactionsCount ==
293 MATCHING_TRANSACTIONS_LIMIT)
295 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
296 "profile = ? and id < ?",
297 new Object[]{profile.getUuid(),
300 progress.setTotal(progress.getProgress());
301 publishProgress(progress);
306 profile.storeTransaction(transaction);
307 matchedTransactionsCount = 0;
308 progress.setTotal(maxTransactionId);
311 state = ParserState.EXPECTING_TRANSACTION;
313 "transaction %s saved → expecting transaction",
314 transaction.getId()));
315 transaction.finishLoading();
317 // sounds like a good idea, but transaction-1 may not be the first one chronologically
318 // for example, when you add the initial seeding transaction after entering some others
319 // if (transactionId == 1) {
320 // L("This was the initial transaction. Terminating " +
326 m = reTransactionDetails.matcher(line);
328 String acc_name = m.group(1);
329 String amount = m.group(2);
330 String currency = m.group(3);
331 if (currency == null) currency = "";
332 amount = amount.replace(',', '.');
333 transaction.addAccount(
334 new LedgerTransactionAccount(acc_name,
335 Float.valueOf(amount), currency));
336 L(String.format("%d: %s = %s", transaction.getId(),
339 else throw new IllegalStateException(String.format(
340 "Can't parse transaction %d " + "details: %s",
341 transactionId, line));
345 throw new RuntimeException(
346 String.format("Unknown parser updating %s",
353 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
354 new String[]{profile.getUuid()});
355 db.setTransactionSuccessful();
357 Log.d("db", "Updating transaction value stamp");
358 Date now = new Date();
359 profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
360 Data.lastUpdateDate.set(now);
361 TransactionListViewModel.scheduleTransactionListReload();
371 catch (MalformedURLException e) {
373 return "Invalid server URL";
375 catch (FileNotFoundException e) {
377 return "Invalid user name or password";
379 catch (IOException e) {
381 return "Network error";
383 catch (OperationCanceledException e) {
385 return "Operation cancelled";
388 Data.backgroundTaskCount.decrementAndGet();
391 private MainActivity getContext() {
392 return contextRef.get();
394 private void throwIfCancelled() {
395 if (isCancelled()) throw new OperationCanceledException(null);
398 private enum ParserState {
399 EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
400 EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
403 public class Progress {
404 public static final int INDETERMINATE = -1;
405 private int progress;
408 this(INDETERMINATE, INDETERMINATE);
410 Progress(int progress, int total) {
411 this.progress = progress;
414 public int getProgress() {
417 protected void setProgress(int progress) {
418 this.progress = progress;
420 public int getTotal() {
423 protected void setTotal(int total) {
428 private class TransactionParserException extends IllegalStateException {
429 TransactionParserException(String message) {