]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
gap-fill missing parent accounts in the hierarchy
[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     public static final int MATCHING_TRANSACTIONS_LIMIT = 50;
56     public 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     protected WeakReference<MainActivity> contextRef;
65     protected int error;
66     Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
67     Pattern account_value_re = Pattern.compile(
68             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
69     Pattern tr_end_re = Pattern.compile("</tr>");
70     Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
71     Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
72     // %3A is '='
73     private boolean success;
74     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
75         this.contextRef = contextRef;
76     }
77     private static final void L(String msg) {
78         Log.d("transaction-parser", msg);
79     }
80     @Override
81     protected void onProgressUpdate(Progress... values) {
82         super.onProgressUpdate(values);
83         MainActivity context = getContext();
84         if (context == null) return;
85         context.onRetrieveProgress(values[0]);
86     }
87     @Override
88     protected void onPreExecute() {
89         super.onPreExecute();
90         MainActivity context = getContext();
91         if (context == null) return;
92         context.onRetrieveStart();
93     }
94     @Override
95     protected void onPostExecute(Void aVoid) {
96         super.onPostExecute(aVoid);
97         MainActivity context = getContext();
98         if (context == null) return;
99         context.onRetrieveDone(success);
100     }
101     @Override
102     protected void onCancelled() {
103         super.onCancelled();
104         MainActivity context = getContext();
105         if (context == null) return;
106         context.onRetrieveDone(false);
107     }
108     @SuppressLint("DefaultLocale")
109     @Override
110     protected Void doInBackground(Void... params) {
111         MobileLedgerProfile profile = Data.profile.get();
112         Progress progress = new Progress();
113         int maxTransactionId = Progress.INDETERMINATE;
114         success = false;
115         ArrayList<LedgerAccount> accountList = new ArrayList<>();
116         ArrayList<LedgerTransaction> transactionList = new ArrayList<>();
117         HashMap<String, Void> accountNames = new HashMap<>();
118         LedgerAccount lastAccount = null;
119         Data.backgroundTaskCount.incrementAndGet();
120         try {
121             HttpURLConnection http = NetworkUtil.prepare_connection("journal");
122             http.setAllowUserInteraction(false);
123             publishProgress(progress);
124             MainActivity ctx = getContext();
125             if (ctx == null) return null;
126             try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
127                 try (InputStream resp = http.getInputStream()) {
128                     if (http.getResponseCode() != 200) throw new IOException(
129                             String.format("HTTP error %d", http.getResponseCode()));
130                     db.beginTransaction();
131                     try {
132                         String ledgerTitle = null;
133
134                         db.execSQL("UPDATE transactions set keep=0");
135                         db.execSQL("update account_values set keep=0;");
136                         db.execSQL("update accounts set keep=0;");
137
138                         ParserState state = ParserState.EXPECTING_ACCOUNT;
139                         String line;
140                         BufferedReader buf =
141                                 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
142
143                         int processedTransactionCount = 0;
144                         int transactionId = 0;
145                         int matchedTransactionsCount = 0;
146                         LedgerTransaction transaction = null;
147                         LINES:
148                         while ((line = buf.readLine()) != null) {
149                             throwIfCancelled();
150                             Matcher m;
151                             m = commentPattern.matcher(line);
152                             if (m.find()) {
153                                 // TODO: comments are ignored for now
154                                 Log.v("transaction-parser", "Ignoring comment");
155                                 continue;
156                             }
157                             //L(String.format("State is %d", updating));
158                             switch (state) {
159                                 case EXPECTING_ACCOUNT:
160                                     if (line.equals("<h2>General Journal</h2>")) {
161                                         state = ParserState.EXPECTING_TRANSACTION;
162                                         L("→ expecting transaction");
163                                         Data.accounts.set(accountList);
164                                         continue;
165                                     }
166                                     m = account_name_re.matcher(line);
167                                     if (m.find()) {
168                                         String acct_encoded = m.group(1);
169                                         String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
170                                         acct_name = acct_name.replace("\"", "");
171                                         L(String.format("found account: %s", acct_name));
172
173                                         profile.storeAccount(acct_name);
174                                         lastAccount = new LedgerAccount(acct_name);
175
176                                         // make sure the parent account(s) are present,
177                                         // synthesising them if necessary
178                                         String parentName = lastAccount.getParentName();
179                                         if (parentName != null) {
180                                             Stack<String> toAppend = new Stack<>();
181                                             while (parentName != null) {
182                                                 if (accountNames.containsKey(parentName)) break;
183                                                 toAppend.push(parentName);
184                                                 parentName = new LedgerAccount(parentName)
185                                                         .getParentName();
186                                             }
187                                             while (!toAppend.isEmpty()) {
188                                                 String aName = toAppend.pop();
189                                                 LedgerAccount acc = new LedgerAccount(aName);
190                                                 accountList.add(acc);
191                                                 L(String.format("gap-filling with %s", aName));
192                                                 accountNames.put(aName, null);
193                                                 profile.storeAccount(aName);
194                                             }
195                                         }
196
197                                         accountList.add(lastAccount);
198                                         accountNames.put(acct_name, null);
199
200                                         state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
201                                         L("→ expecting account amount");
202                                     }
203                                     break;
204
205                                 case EXPECTING_ACCOUNT_AMOUNT:
206                                     m = account_value_re.matcher(line);
207                                     boolean match_found = false;
208                                     while (m.find()) {
209                                         throwIfCancelled();
210
211                                         match_found = true;
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);
220                                     }
221
222                                     if (match_found) {
223                                         state = ParserState.EXPECTING_ACCOUNT;
224                                         L("→ expecting account");
225                                     }
226
227                                     break;
228
229                                 case EXPECTING_TRANSACTION:
230                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
231                                     m = transactionStartPattern.matcher(line);
232                                     if (m.find()) {
233                                         transactionId = Integer.valueOf(m.group(1));
234                                         state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
235                                         L(String.format(
236                                                 "found transaction %d → expecting description",
237                                                 transactionId));
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);
245                                     }
246                                     m = endPattern.matcher(line);
247                                     if (m.find()) {
248                                         L("--- transaction value complete ---");
249                                         success = true;
250                                         break LINES;
251                                     }
252                                     break;
253
254                                 case EXPECTING_TRANSACTION_DESCRIPTION:
255                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
256                                     m = transactionDescriptionPattern.matcher(line);
257                                     if (m.find()) {
258                                         if (transactionId == 0)
259                                             throw new TransactionParserException(
260                                                     "Transaction Id is 0 while expecting " +
261                                                     "description");
262
263                                         transaction =
264                                                 new LedgerTransaction(transactionId, m.group(1),
265                                                         m.group(2));
266                                         state = ParserState.EXPECTING_TRANSACTION_DETAILS;
267                                         L(String.format("transaction %d created for %s (%s) →" +
268                                                         " expecting details", transactionId,
269                                                 m.group(1), m.group(2)));
270                                     }
271                                     break;
272
273                                 case EXPECTING_TRANSACTION_DETAILS:
274                                     if (line.isEmpty()) {
275                                         // transaction data collected
276                                         if (transaction.existsInDb(db)) {
277                                             db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
278                                                        "profile = ? and id=?",
279                                                     new Object[]{profile.getUuid(),
280                                                                  transaction.getId()
281                                                     });
282                                             matchedTransactionsCount++;
283
284                                             if (matchedTransactionsCount ==
285                                                 MATCHING_TRANSACTIONS_LIMIT)
286                                             {
287                                                 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
288                                                            "profile = ? and id < ?",
289                                                         new Object[]{profile.getUuid(),
290                                                                      transaction.getId()
291                                                         });
292                                                 success = true;
293                                                 progress.setTotal(progress.getProgress());
294                                                 publishProgress(progress);
295                                                 break LINES;
296                                             }
297                                         }
298                                         else {
299                                             profile.storeTransaction(transaction);
300                                             matchedTransactionsCount = 0;
301                                             progress.setTotal(maxTransactionId);
302                                         }
303
304                                         state = ParserState.EXPECTING_TRANSACTION;
305                                         L(String.format(
306                                                 "transaction %s saved → expecting transaction",
307                                                 transaction.getId()));
308                                         transaction.finishLoading();
309                                         transactionList.add(transaction);
310
311 // sounds like a good idea, but transaction-1 may not be the first one chronologically
312 // for example, when you add the initial seeding transaction after entering some others
313 //                                            if (transactionId == 1) {
314 //                                                L("This was the initial transaction. Terminating " +
315 //                                                  "parser");
316 //                                                break LINES;
317 //                                            }
318                                     }
319                                     else {
320                                         m = transactionDetailsPattern.matcher(line);
321                                         if (m.find()) {
322                                             String acc_name = m.group(1);
323                                             String amount = m.group(2);
324                                             String currency = m.group(3);
325                                             if (currency == null) currency = "";
326                                             amount = amount.replace(',', '.');
327                                             transaction.addAccount(
328                                                     new LedgerTransactionAccount(acc_name,
329                                                             Float.valueOf(amount), currency));
330                                             L(String.format("%d: %s = %s", transaction.getId(),
331                                                     acc_name, amount));
332                                         }
333                                         else throw new IllegalStateException(String.format(
334                                                 "Can't parse transaction %d " + "details: %s",
335                                                 transactionId, line));
336                                     }
337                                     break;
338                                 default:
339                                     throw new RuntimeException(
340                                             String.format("Unknown parser updating %s",
341                                                     state.name()));
342                             }
343                         }
344
345                         throwIfCancelled();
346
347                         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
348                                 new String[]{profile.getUuid()});
349                         db.setTransactionSuccessful();
350
351                         Log.d("db", "Updating transaction value stamp");
352                         Date now = new Date();
353                         profile.set_option_value(MLDB.OPT_LAST_SCRAPE, now.getTime());
354                         Data.lastUpdateDate.set(now);
355                         Data.transactions.set(transactionList);
356                     }
357                     finally {
358                         db.endTransaction();
359                     }
360                 }
361             }
362         }
363         catch (MalformedURLException e) {
364             error = R.string.err_bad_backend_url;
365             e.printStackTrace();
366         }
367         catch (FileNotFoundException e) {
368             error = R.string.err_bad_auth;
369             e.printStackTrace();
370         }
371         catch (IOException e) {
372             error = R.string.err_net_io_error;
373             e.printStackTrace();
374         }
375         catch (OperationCanceledException e) {
376             error = R.string.err_cancelled;
377             e.printStackTrace();
378         }
379         finally {
380             Data.backgroundTaskCount.decrementAndGet();
381         }
382         return null;
383     }
384     private MainActivity getContext() {
385         return contextRef.get();
386     }
387     private void throwIfCancelled() {
388         if (isCancelled()) throw new OperationCanceledException(null);
389     }
390
391     private enum ParserState {
392         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
393         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
394     }
395
396     public class Progress {
397         public static final int INDETERMINATE = -1;
398         private int progress;
399         private int total;
400         Progress() {
401             this(INDETERMINATE, INDETERMINATE);
402         }
403         Progress(int progress, int total) {
404             this.progress = progress;
405             this.total = total;
406         }
407         public int getProgress() {
408             return progress;
409         }
410         protected void setProgress(int progress) {
411             this.progress = progress;
412         }
413         public int getTotal() {
414             return total;
415         }
416         protected void setTotal(int total) {
417             this.total = total;
418         }
419     }
420
421     private class TransactionParserException extends IllegalStateException {
422         TransactionParserException(String message) {
423             super(message);
424         }
425     }
426 }