]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
4e2c6108f5d1eb79f74d8898b8b25899d8f2fdf5
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveTransactionsTask.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.async;
19
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;
25
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;
35
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.HashMap;
48 import java.util.Stack;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
51
52
53 public class RetrieveTransactionsTask
54         extends AsyncTask<Void, RetrieveTransactionsTask.Progress, Void> {
55     private static final int MATCHING_TRANSACTIONS_LIMIT = 50;
56     private static final Pattern commentPattern = Pattern.compile("^\\s*;");
57     private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
58                                                                            "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
59     private static final Pattern transactionDescriptionPattern =
60             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
61     private static final Pattern transactionDetailsPattern =
62             Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
63     private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
64     private WeakReference<MainActivity> contextRef;
65     private int error;
66     // %3A is '='
67     private boolean success;
68     private Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
69     private Pattern account_value_re = Pattern.compile(
70             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
71     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
72         this.contextRef = contextRef;
73     }
74     private static void L(String msg) {
75         Log.d("transaction-parser", msg);
76     }
77     @Override
78     protected void onProgressUpdate(Progress... values) {
79         super.onProgressUpdate(values);
80         MainActivity context = getContext();
81         if (context == null) return;
82         context.onRetrieveProgress(values[0]);
83     }
84     @Override
85     protected void onPreExecute() {
86         super.onPreExecute();
87         MainActivity context = getContext();
88         if (context == null) return;
89         context.onRetrieveStart();
90     }
91     @Override
92     protected void onPostExecute(Void aVoid) {
93         super.onPostExecute(aVoid);
94         MainActivity context = getContext();
95         if (context == null) return;
96         context.onRetrieveDone(success);
97     }
98     @Override
99     protected void onCancelled() {
100         super.onCancelled();
101         MainActivity context = getContext();
102         if (context == null) return;
103         context.onRetrieveDone(false);
104     }
105     @SuppressLint("DefaultLocale")
106     @Override
107     protected Void doInBackground(Void... params) {
108         MobileLedgerProfile profile = Data.profile.get();
109         Progress progress = new Progress();
110         int maxTransactionId = Progress.INDETERMINATE;
111         success = false;
112         ArrayList<LedgerAccount> accountList = new ArrayList<>();
113         ArrayList<LedgerTransaction> transactionList = new ArrayList<>();
114         HashMap<String, Void> accountNames = new HashMap<>();
115         LedgerAccount lastAccount = null;
116         boolean onlyStarred = Data.optShowOnlyStarred.get();
117         Data.backgroundTaskCount.incrementAndGet();
118         try {
119             HttpURLConnection http = NetworkUtil.prepare_connection("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();
129                     try {
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;");
133
134                         ParserState state = ParserState.EXPECTING_ACCOUNT;
135                         String line;
136                         BufferedReader buf =
137                                 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
138
139                         int processedTransactionCount = 0;
140                         int transactionId = 0;
141                         int matchedTransactionsCount = 0;
142                         LedgerTransaction transaction = null;
143                         LINES:
144                         while ((line = buf.readLine()) != null) {
145                             throwIfCancelled();
146                             Matcher m;
147                             m = commentPattern.matcher(line);
148                             if (m.find()) {
149                                 // TODO: comments are ignored for now
150                                 Log.v("transaction-parser", "Ignoring comment");
151                                 continue;
152                             }
153                             //L(String.format("State is %d", updating));
154                             switch (state) {
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);
160                                         continue;
161                                     }
162                                     m = account_name_re.matcher(line);
163                                     if (m.find()) {
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));
168
169                                         lastAccount = profile.loadAccount(acct_name);
170                                         if (lastAccount == null) {
171                                             lastAccount = new LedgerAccount(acct_name);
172                                             profile.storeAccount(lastAccount);
173                                         }
174
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)
184                                                         .getParentName();
185                                             }
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);
195                                             }
196                                         }
197
198                                         if (!onlyStarred || !lastAccount.isHidden())
199                                             accountList.add(lastAccount);
200                                         accountNames.put(acct_name, null);
201
202                                         state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
203                                         L("→ expecting account amount");
204                                     }
205                                     break;
206
207                                 case EXPECTING_ACCOUNT_AMOUNT:
208                                     m = account_value_re.matcher(line);
209                                     boolean match_found = false;
210                                     while (m.find()) {
211                                         throwIfCancelled();
212
213                                         match_found = true;
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);
222                                     }
223
224                                     if (match_found) {
225                                         state = ParserState.EXPECTING_ACCOUNT;
226                                         L("→ expecting account");
227                                     }
228
229                                     break;
230
231                                 case EXPECTING_TRANSACTION:
232                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
233                                     m = transactionStartPattern.matcher(line);
234                                     if (m.find()) {
235                                         transactionId = Integer.valueOf(m.group(1));
236                                         state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
237                                         L(String.format(
238                                                 "found transaction %d → expecting description",
239                                                 transactionId));
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);
247                                     }
248                                     m = endPattern.matcher(line);
249                                     if (m.find()) {
250                                         L("--- transaction value complete ---");
251                                         success = true;
252                                         break LINES;
253                                     }
254                                     break;
255
256                                 case EXPECTING_TRANSACTION_DESCRIPTION:
257                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
258                                     m = transactionDescriptionPattern.matcher(line);
259                                     if (m.find()) {
260                                         if (transactionId == 0)
261                                             throw new TransactionParserException(
262                                                     "Transaction Id is 0 while expecting " +
263                                                     "description");
264
265                                         transaction =
266                                                 new LedgerTransaction(transactionId, m.group(1),
267                                                         m.group(2));
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)));
272                                     }
273                                     break;
274
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(),
282                                                                  transaction.getId()
283                                                     });
284                                             matchedTransactionsCount++;
285
286                                             if (matchedTransactionsCount ==
287                                                 MATCHING_TRANSACTIONS_LIMIT)
288                                             {
289                                                 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
290                                                            "profile = ? and id < ?",
291                                                         new Object[]{profile.getUuid(),
292                                                                      transaction.getId()
293                                                         });
294                                                 success = true;
295                                                 progress.setTotal(progress.getProgress());
296                                                 publishProgress(progress);
297                                                 break LINES;
298                                             }
299                                         }
300                                         else {
301                                             profile.storeTransaction(transaction);
302                                             matchedTransactionsCount = 0;
303                                             progress.setTotal(maxTransactionId);
304                                         }
305
306                                         state = ParserState.EXPECTING_TRANSACTION;
307                                         L(String.format(
308                                                 "transaction %s saved → expecting transaction",
309                                                 transaction.getId()));
310                                         transaction.finishLoading();
311                                         transactionList.add(transaction);
312
313 // sounds like a good idea, but transaction-1 may not be the first one chronologically
314 // for example, when you add the initial seeding transaction after entering some others
315 //                                            if (transactionId == 1) {
316 //                                                L("This was the initial transaction. Terminating " +
317 //                                                  "parser");
318 //                                                break LINES;
319 //                                            }
320                                     }
321                                     else {
322                                         m = transactionDetailsPattern.matcher(line);
323                                         if (m.find()) {
324                                             String acc_name = m.group(1);
325                                             String amount = m.group(2);
326                                             String currency = m.group(3);
327                                             if (currency == null) currency = "";
328                                             amount = amount.replace(',', '.');
329                                             transaction.addAccount(
330                                                     new LedgerTransactionAccount(acc_name,
331                                                             Float.valueOf(amount), currency));
332                                             L(String.format("%d: %s = %s", transaction.getId(),
333                                                     acc_name, amount));
334                                         }
335                                         else throw new IllegalStateException(String.format(
336                                                 "Can't parse transaction %d " + "details: %s",
337                                                 transactionId, line));
338                                     }
339                                     break;
340                                 default:
341                                     throw new RuntimeException(
342                                             String.format("Unknown parser updating %s",
343                                                     state.name()));
344                             }
345                         }
346
347                         throwIfCancelled();
348
349                         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
350                                 new String[]{profile.getUuid()});
351                         db.setTransactionSuccessful();
352
353                         Log.d("db", "Updating transaction value stamp");
354                         Date now = new Date();
355                         profile.set_option_value(MLDB.OPT_LAST_SCRAPE, now.getTime());
356                         Data.lastUpdateDate.set(now);
357                         Data.transactions.set(transactionList);
358                     }
359                     finally {
360                         db.endTransaction();
361                     }
362                 }
363             }
364         }
365         catch (MalformedURLException e) {
366             error = R.string.err_bad_backend_url;
367             e.printStackTrace();
368         }
369         catch (FileNotFoundException e) {
370             error = R.string.err_bad_auth;
371             e.printStackTrace();
372         }
373         catch (IOException e) {
374             error = R.string.err_net_io_error;
375             e.printStackTrace();
376         }
377         catch (OperationCanceledException e) {
378             error = R.string.err_cancelled;
379             e.printStackTrace();
380         }
381         finally {
382             Data.backgroundTaskCount.decrementAndGet();
383         }
384         return null;
385     }
386     private MainActivity getContext() {
387         return contextRef.get();
388     }
389     private void throwIfCancelled() {
390         if (isCancelled()) throw new OperationCanceledException(null);
391     }
392
393     private enum ParserState {
394         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
395         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
396     }
397
398     public class Progress {
399         public static final int INDETERMINATE = -1;
400         private int progress;
401         private int total;
402         Progress() {
403             this(INDETERMINATE, INDETERMINATE);
404         }
405         Progress(int progress, int total) {
406             this.progress = progress;
407             this.total = total;
408         }
409         public int getProgress() {
410             return progress;
411         }
412         protected void setProgress(int progress) {
413             this.progress = progress;
414         }
415         public int getTotal() {
416             return total;
417         }
418         protected void setTotal(int total) {
419             this.total = total;
420         }
421     }
422
423     private class TransactionParserException extends IllegalStateException {
424         TransactionParserException(String message) {
425             super(message);
426         }
427     }
428 }