]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
whitespace
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveTransactionsTask.java
1 /*
2  * Copyright © 2020 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe 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  * MoLe 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 MoLe. 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
25 import androidx.annotation.NonNull;
26
27 import net.ktnx.mobileledger.App;
28 import net.ktnx.mobileledger.err.HTTPException;
29 import net.ktnx.mobileledger.json.v1_15.AccountListParser;
30 import net.ktnx.mobileledger.json.v1_15.ParsedBalance;
31 import net.ktnx.mobileledger.json.v1_15.ParsedLedgerAccount;
32 import net.ktnx.mobileledger.json.v1_15.ParsedLedgerTransaction;
33 import net.ktnx.mobileledger.json.v1_15.TransactionListParser;
34 import net.ktnx.mobileledger.model.Data;
35 import net.ktnx.mobileledger.model.LedgerAccount;
36 import net.ktnx.mobileledger.model.LedgerTransaction;
37 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
38 import net.ktnx.mobileledger.model.MobileLedgerProfile;
39 import net.ktnx.mobileledger.ui.activity.MainActivity;
40 import net.ktnx.mobileledger.utils.NetworkUtil;
41
42 import java.io.BufferedReader;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.InputStreamReader;
46 import java.lang.ref.WeakReference;
47 import java.net.HttpURLConnection;
48 import java.net.MalformedURLException;
49 import java.net.URLDecoder;
50 import java.nio.charset.StandardCharsets;
51 import java.text.ParseException;
52 import java.util.ArrayList;
53 import java.util.HashMap;
54 import java.util.Locale;
55 import java.util.Objects;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
58
59
60 public class RetrieveTransactionsTask
61         extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
62     private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
63     private static final Pattern reComment = Pattern.compile("^\\s*;");
64     private static final Pattern reTransactionStart = Pattern.compile(
65             "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
66             "\"[^\"]*>([\\d.-]+)</td>");
67     private static final Pattern reTransactionDescription =
68             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
69     private static final Pattern reTransactionDetails = Pattern.compile(
70             "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
71             "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
72     private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
73     private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
74     private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
75     private WeakReference<MainActivity> contextRef;
76     // %3A is '='
77     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
78     private Pattern reAccountValue = Pattern.compile(
79             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
80     private MobileLedgerProfile profile;
81     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
82                                     @NonNull MobileLedgerProfile profile) {
83         this.contextRef = contextRef;
84         this.profile = profile;
85     }
86     private static void L(String msg) {
87         //debug("transaction-parser", msg);
88     }
89     static LedgerTransactionAccount parseTransactionAccountLine(String line) {
90         Matcher m = reTransactionDetails.matcher(line);
91         if (m.find()) {
92             String postingStatus = m.group(1);
93             String acc_name = m.group(2);
94             String currencyPre = m.group(3);
95             String amount = Objects.requireNonNull(m.group(4));
96             String currencyPost = m.group(5);
97
98             String currency = null;
99             if ((currencyPre != null) && (currencyPre.length() > 0)) {
100                 if ((currencyPost != null) && (currencyPost.length() > 0))
101                     return null;
102                 currency = currencyPre;
103             }
104             else if ((currencyPost != null) && (currencyPost.length() > 0)) {
105                 currency = currencyPost;
106             }
107
108             amount = amount.replace(',', '.');
109
110             return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
111         }
112         else {
113             return null;
114         }
115     }
116     @Override
117     protected void onProgressUpdate(Progress... values) {
118         super.onProgressUpdate(values);
119         Data.backgroundTaskProgress.postValue(values[0]);
120     }
121     @Override
122     protected void onPreExecute() {
123         super.onPreExecute();
124         MainActivity context = getContext();
125         if (context == null)
126             return;
127         context.onRetrieveStart();
128     }
129     @Override
130     protected void onPostExecute(String error) {
131         super.onPostExecute(error);
132         Progress progress = new Progress();
133         progress.setState(ProgressState.FINISHED);
134         progress.setError(error);
135         onProgressUpdate(progress);
136     }
137     @Override
138     protected void onCancelled() {
139         super.onCancelled();
140         Progress progress = new Progress();
141         progress.setState(ProgressState.FINISHED);
142         onProgressUpdate(progress);
143     }
144     private String retrieveTransactionListLegacy() throws IOException, HTTPException {
145         Progress progress = Progress.indeterminate();
146         progress.setState(ProgressState.RUNNING);
147         int maxTransactionId = -1;
148         ArrayList<LedgerAccount> list = new ArrayList<>();
149         HashMap<String, LedgerAccount> map = new HashMap<>();
150         ArrayList<LedgerAccount> displayed = new ArrayList<>();
151         ArrayList<LedgerTransaction> transactions = new ArrayList<>();
152         LedgerAccount lastAccount = null;
153         ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
154
155         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
156         http.setAllowUserInteraction(false);
157         publishProgress(progress);
158         if (http.getResponseCode() != 200)
159             throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
160
161         try (InputStream resp = http.getInputStream()) {
162             if (http.getResponseCode() != 200)
163                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
164
165             int matchedTransactionsCount = 0;
166
167             ParserState state = ParserState.EXPECTING_ACCOUNT;
168             String line;
169             BufferedReader buf =
170                     new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
171
172             int processedTransactionCount = 0;
173             int transactionId = 0;
174             LedgerTransaction transaction = null;
175             LINES:
176             while ((line = buf.readLine()) != null) {
177                 throwIfCancelled();
178                 Matcher m;
179                 m = reComment.matcher(line);
180                 if (m.find()) {
181                     // TODO: comments are ignored for now
182 //                            Log.v("transaction-parser", "Ignoring comment");
183                     continue;
184                 }
185                 //L(String.format("State is %d", updating));
186                 switch (state) {
187                     case EXPECTING_ACCOUNT:
188                         if (line.equals("<h2>General Journal</h2>")) {
189                             state = ParserState.EXPECTING_TRANSACTION;
190                             L("→ expecting transaction");
191                             continue;
192                         }
193                         m = reAccountName.matcher(line);
194                         if (m.find()) {
195                             String acct_encoded = m.group(1);
196                             String accName = URLDecoder.decode(acct_encoded, "UTF-8");
197                             accName = accName.replace("\"", "");
198                             L(String.format("found account: %s", accName));
199
200                             lastAccount = map.get(accName);
201                             if (lastAccount != null) {
202                                 L(String.format("ignoring duplicate account '%s'", accName));
203                                 continue;
204                             }
205                             String parentAccountName = LedgerAccount.extractParentName(accName);
206                             LedgerAccount parentAccount;
207                             if (parentAccountName != null) {
208                                 parentAccount = ensureAccountExists(parentAccountName, map,
209                                         syntheticAccounts);
210                             }
211                             else {
212                                 parentAccount = null;
213                             }
214                             lastAccount = new LedgerAccount(profile, accName, parentAccount);
215
216                             list.add(lastAccount);
217                             map.put(accName, lastAccount);
218
219                             state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
220                             L("→ expecting account amount");
221                         }
222                         break;
223
224                     case EXPECTING_ACCOUNT_AMOUNT:
225                         m = reAccountValue.matcher(line);
226                         boolean match_found = false;
227                         while (m.find()) {
228                             throwIfCancelled();
229
230                             match_found = true;
231                             String value = Objects.requireNonNull(m.group(1));
232                             String currency = m.group(2);
233                             if (currency == null)
234                                 currency = "";
235
236                             {
237                                 Matcher tmpM = reDecimalComma.matcher(value);
238                                 if (tmpM.find()) {
239                                     value = value.replace(".", "");
240                                     value = value.replace(',', '.');
241                                 }
242
243                                 tmpM = reDecimalPoint.matcher(value);
244                                 if (tmpM.find()) {
245                                     value = value.replace(",", "");
246                                     value = value.replace(" ", "");
247                                 }
248                             }
249                             L("curr=" + currency + ", value=" + value);
250                             final float val = Float.parseFloat(value);
251                             lastAccount.addAmount(val, currency);
252                             for (LedgerAccount syn : syntheticAccounts) {
253                                 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
254                                         currency, val, syn.getName()));
255                                 syn.addAmount(val, currency);
256                             }
257                         }
258
259                         if (match_found) {
260                             syntheticAccounts.clear();
261                             state = ParserState.EXPECTING_ACCOUNT;
262                             L("→ expecting account");
263                         }
264
265                         break;
266
267                     case EXPECTING_TRANSACTION:
268                         if (!line.isEmpty() && (line.charAt(0) == ' '))
269                             continue;
270                         m = reTransactionStart.matcher(line);
271                         if (m.find()) {
272                             transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
273                             state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
274                             L(String.format(Locale.ENGLISH,
275                                     "found transaction %d → expecting description", transactionId));
276                             progress.setProgress(++processedTransactionCount);
277                             if (maxTransactionId < transactionId)
278                                 maxTransactionId = transactionId;
279                             if ((progress.isIndeterminate()) ||
280                                 (progress.getTotal() < transactionId))
281                                 progress.setTotal(transactionId);
282                             publishProgress(progress);
283                         }
284                         m = reEnd.matcher(line);
285                         if (m.find()) {
286                             L("--- transaction value complete ---");
287                             break LINES;
288                         }
289                         break;
290
291                     case EXPECTING_TRANSACTION_DESCRIPTION:
292                         if (!line.isEmpty() && (line.charAt(0) == ' '))
293                             continue;
294                         m = reTransactionDescription.matcher(line);
295                         if (m.find()) {
296                             if (transactionId == 0)
297                                 throw new TransactionParserException(
298                                         "Transaction Id is 0 while expecting " + "description");
299
300                             String date = Objects.requireNonNull(m.group(1));
301                             try {
302                                 int equalsIndex = date.indexOf('=');
303                                 if (equalsIndex >= 0)
304                                     date = date.substring(equalsIndex + 1);
305                                 transaction =
306                                         new LedgerTransaction(transactionId, date, m.group(2));
307                             }
308                             catch (ParseException e) {
309                                 e.printStackTrace();
310                                 return String.format("Error parsing date '%s'", date);
311                             }
312                             state = ParserState.EXPECTING_TRANSACTION_DETAILS;
313                             L(String.format(Locale.ENGLISH,
314                                     "transaction %d created for %s (%s) →" + " expecting details",
315                                     transactionId, date, m.group(2)));
316                         }
317                         break;
318
319                     case EXPECTING_TRANSACTION_DETAILS:
320                         if (line.isEmpty()) {
321                             // transaction data collected
322
323                             transaction.finishLoading();
324                             transactions.add(transaction);
325
326                             state = ParserState.EXPECTING_TRANSACTION;
327                             L(String.format("transaction %s parsed → expecting transaction",
328                                     transaction.getId()));
329
330 // sounds like a good idea, but transaction-1 may not be the first one chronologically
331 // for example, when you add the initial seeding transaction after entering some others
332 //                                            if (transactionId == 1) {
333 //                                                L("This was the initial transaction.
334 //                                                Terminating " +
335 //                                                  "parser");
336 //                                                break LINES;
337 //                                            }
338                         }
339                         else {
340                             LedgerTransactionAccount lta = parseTransactionAccountLine(line);
341                             if (lta != null) {
342                                 transaction.addAccount(lta);
343                                 L(String.format(Locale.ENGLISH, "%d: %s = %s", transaction.getId(),
344                                         lta.getAccountName(), lta.getAmount()));
345                             }
346                             else
347                                 throw new IllegalStateException(
348                                         String.format("Can't parse transaction %d details: %s",
349                                                 transactionId, line));
350                         }
351                         break;
352                     default:
353                         throw new RuntimeException(
354                                 String.format("Unknown parser updating %s", state.name()));
355                 }
356             }
357
358             throwIfCancelled();
359
360             profile.setAndStoreAccountAndTransactionListFromWeb(list, transactions);
361
362             return null;
363         }
364     }
365     private @NonNull
366     LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
367                                       ArrayList<LedgerAccount> createdAccounts) {
368         LedgerAccount acc = map.get(accountName);
369
370         if (acc != null)
371             return acc;
372
373         String parentName = LedgerAccount.extractParentName(accountName);
374         LedgerAccount parentAccount;
375         if (parentName != null) {
376             parentAccount = ensureAccountExists(parentName, map, createdAccounts);
377         }
378         else {
379             parentAccount = null;
380         }
381
382         acc = new LedgerAccount(profile, accountName, parentAccount);
383         createdAccounts.add(acc);
384         return acc;
385     }
386     private boolean retrieveAccountList() throws IOException, HTTPException {
387         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
388         http.setAllowUserInteraction(false);
389         switch (http.getResponseCode()) {
390             case 200:
391                 break;
392             case 404:
393                 return false;
394             default:
395                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
396         }
397         publishProgress(Progress.indeterminate());
398         SQLiteDatabase db = App.getDatabase();
399         ArrayList<LedgerAccount> list = new ArrayList<>();
400         HashMap<String, LedgerAccount> map = new HashMap<>();
401         HashMap<String, LedgerAccount> currentMap = new HashMap<>();
402         for (LedgerAccount acc : Objects.requireNonNull(profile.getAllAccounts()))
403             currentMap.put(acc.getName(), acc);
404         try (InputStream resp = http.getInputStream()) {
405             if (http.getResponseCode() != 200)
406                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
407
408             AccountListParser parser = new AccountListParser(resp);
409
410             while (true) {
411                 throwIfCancelled();
412                 ParsedLedgerAccount parsedAccount = parser.nextAccount();
413                 if (parsedAccount == null) {
414                     break;
415                 }
416
417                 final String accName = parsedAccount.getAname();
418                 LedgerAccount acc = map.get(accName);
419                 if (acc != null)
420                     throw new RuntimeException(
421                             String.format("Account '%s' already present", acc.getName()));
422                 String parentName = LedgerAccount.extractParentName(accName);
423                 ArrayList<LedgerAccount> createdParents = new ArrayList<>();
424                 LedgerAccount parent;
425                 if (parentName == null) {
426                     parent = null;
427                 }
428                 else {
429                     parent = ensureAccountExists(parentName, map, createdParents);
430                     parent.setHasSubAccounts(true);
431                 }
432                 acc = new LedgerAccount(profile, accName, parent);
433                 list.add(acc);
434                 map.put(accName, acc);
435
436                 String lastCurrency = null;
437                 float lastCurrencyAmount = 0;
438                 for (ParsedBalance b : parsedAccount.getAibalance()) {
439                     throwIfCancelled();
440                     final String currency = b.getAcommodity();
441                     final float amount = b.getAquantity()
442                                           .asFloat();
443                     if (currency.equals(lastCurrency)) {
444                         lastCurrencyAmount += amount;
445                     }
446                     else {
447                         if (lastCurrency != null) {
448                             acc.addAmount(lastCurrencyAmount, lastCurrency);
449                         }
450                         lastCurrency = currency;
451                         lastCurrencyAmount = amount;
452                     }
453                 }
454                 if (lastCurrency != null) {
455                     acc.addAmount(lastCurrencyAmount, lastCurrency);
456                 }
457                 for (LedgerAccount p : createdParents)
458                     acc.propagateAmountsTo(p);
459             }
460             throwIfCancelled();
461         }
462
463         // the current account tree may have changed, update the new-to be tree to match
464         for (LedgerAccount acc : list) {
465             LedgerAccount prevData = currentMap.get(acc.getName());
466             if (prevData != null) {
467                 acc.setExpanded(prevData.isExpanded());
468                 acc.setAmountsExpanded(prevData.amountsExpanded());
469             }
470         }
471
472         profile.setAndStoreAccountListFromWeb(list);
473         return true;
474     }
475     private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
476         Progress progress = new Progress();
477         int maxTransactionId = Data.transactions.size();
478
479         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
480         http.setAllowUserInteraction(false);
481         publishProgress(progress);
482         switch (http.getResponseCode()) {
483             case 200:
484                 break;
485             case 404:
486                 return false;
487             default:
488                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
489         }
490         try (InputStream resp = http.getInputStream()) {
491             throwIfCancelled();
492             ArrayList<LedgerTransaction> trList = new ArrayList<>();
493
494             TransactionListParser parser = new TransactionListParser(resp);
495
496             int processedTransactionCount = 0;
497
498             while (true) {
499                 throwIfCancelled();
500                 ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
501                 throwIfCancelled();
502                 if (parsedTransaction == null)
503                     break;
504
505                 LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
506                 trList.add(transaction);
507
508                 progress.setProgress(++processedTransactionCount);
509                 publishProgress(progress);
510             }
511
512             throwIfCancelled();
513             profile.setAndStoreTransactionList(trList);
514         }
515
516         return true;
517     }
518
519     @SuppressLint("DefaultLocale")
520     @Override
521     protected String doInBackground(Void... params) {
522         Data.backgroundTaskStarted();
523         try {
524             if (!retrieveAccountList() || !retrieveTransactionList())
525                 return retrieveTransactionListLegacy();
526             return null;
527         }
528         catch (MalformedURLException e) {
529             e.printStackTrace();
530             return "Invalid server URL";
531         }
532         catch (HTTPException e) {
533             e.printStackTrace();
534             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
535         }
536         catch (IOException e) {
537             e.printStackTrace();
538             return e.getLocalizedMessage();
539         }
540         catch (ParseException e) {
541             e.printStackTrace();
542             return "Network error";
543         }
544         catch (OperationCanceledException e) {
545             e.printStackTrace();
546             return "Operation cancelled";
547         }
548         finally {
549             Data.backgroundTaskFinished();
550         }
551     }
552     private MainActivity getContext() {
553         return contextRef.get();
554     }
555     private void throwIfCancelled() {
556         if (isCancelled())
557             throw new OperationCanceledException(null);
558     }
559     private enum ParserState {
560         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
561         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
562     }
563
564     public enum ProgressState {STARTING, RUNNING, FINISHED}
565
566     public static class Progress {
567         private int progress;
568         private int total;
569         private ProgressState state = ProgressState.RUNNING;
570         private String error = null;
571         private boolean indeterminate;
572         Progress() {
573             indeterminate = true;
574         }
575         Progress(int progress, int total) {
576             this.indeterminate = false;
577             this.progress = progress;
578             this.total = total;
579         }
580         public static Progress indeterminate() {
581             return new Progress();
582         }
583         public static Progress finished(String error) {
584             Progress p = new Progress();
585             p.setState(ProgressState.FINISHED);
586             p.setError(error);
587             return p;
588         }
589         public int getProgress() {
590             ensureState(ProgressState.RUNNING);
591             return progress;
592         }
593         protected void setProgress(int progress) {
594             this.progress = progress;
595             this.state = ProgressState.RUNNING;
596         }
597         public int getTotal() {
598             ensureState(ProgressState.RUNNING);
599             return total;
600         }
601         protected void setTotal(int total) {
602             this.total = total;
603             state = ProgressState.RUNNING;
604         }
605         private void ensureState(ProgressState wanted) {
606             if (state != wanted)
607                 throw new IllegalStateException(
608                         String.format("Bad state: %s, expected %s", state, wanted));
609         }
610         public ProgressState getState() {
611             return state;
612         }
613         public void setState(ProgressState state) {
614             this.state = state;
615         }
616         public String getError() {
617             ensureState(ProgressState.FINISHED);
618             return error;
619         }
620         public void setError(String error) {
621             this.error = error;
622             state = ProgressState.FINISHED;
623         }
624         public boolean isIndeterminate() {
625             return indeterminate;
626         }
627         public void setIndeterminate(boolean indeterminate) {
628             this.indeterminate = indeterminate;
629         }
630     }
631
632     private static class TransactionParserException extends IllegalStateException {
633         TransactionParserException(String message) {
634             super(message);
635         }
636     }
637 }