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