]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
commit right after the account list is complete
[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.set(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         try (InputStream resp = http.getInputStream()) {
394             if (http.getResponseCode() != 200)
395                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
396
397             db.beginTransaction();
398             try {
399                 profile.markAccountsAsNotPresent(db);
400
401                 AccountListParser parser = new AccountListParser(resp);
402                 ArrayList<LedgerAccount> accountList = new ArrayList<>();
403
404                 LedgerAccount prevAccount = null;
405
406                 while (true) {
407                     throwIfCancelled();
408                     ParsedLedgerAccount parsedAccount = parser.nextAccount();
409                     if (parsedAccount == null) break;
410
411                     LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
412                     if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
413                     else acc.removeAmounts();
414
415                     profile.storeAccount(db, acc);
416                     for (ParsedBalance b : parsedAccount.getAebalance()) {
417                         profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
418                                 b.getAquantity().asFloat());
419                     }
420
421                     if (acc.isVisible(accountList)) accountList.add(acc);
422
423                     if (prevAccount != null) {
424                         prevAccount.setHasSubAccounts(
425                                 acc.getName().startsWith(prevAccount.getName() + ":"));
426                     }
427
428                     prevAccount = acc;
429                 }
430                 throwIfCancelled();
431
432                 profile.deleteNotPresentAccounts(db);
433                 throwIfCancelled();
434                 db.setTransactionSuccessful();
435                 Data.accounts.set(accountList);
436             }
437             finally {
438                 db.endTransaction();
439             }
440         }
441
442         return true;
443     }
444     private boolean retrieveTransactionList(MobileLedgerProfile profile)
445             throws IOException, ParseException, HTTPException {
446         Progress progress = new Progress();
447         int maxTransactionId = Progress.INDETERMINATE;
448
449         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
450         http.setAllowUserInteraction(false);
451         publishProgress(progress);
452         switch (http.getResponseCode()) {
453             case 200:
454                 break;
455             case 404:
456                 return false;
457             default:
458                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
459         }
460         try (SQLiteDatabase db = MLDB.getDatabase()) {
461             try (InputStream resp = http.getInputStream()) {
462                 if (http.getResponseCode() != 200)
463                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
464                 throwIfCancelled();
465                 db.beginTransaction();
466                 try {
467                     profile.markTransactionsAsNotPresent(db);
468
469                     int matchedTransactionsCount = 0;
470                     TransactionListParser parser = new TransactionListParser(resp);
471
472                     int processedTransactionCount = 0;
473
474                     while (true) {
475                         throwIfCancelled();
476                         ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
477                         throwIfCancelled();
478                         if (parsedTransaction == null) break;
479                         LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
480                         if (transaction.existsInDb(db)) {
481                             profile.markTransactionAsPresent(db, transaction);
482                             matchedTransactionsCount++;
483
484                             if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
485                                 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
486                                 progress.setTotal(progress.getProgress());
487                                 publishProgress(progress);
488                                 db.setTransactionSuccessful();
489                                 profile.setLastUpdateStamp();
490                                 return true;
491                             }
492                         }
493                         else {
494                             profile.storeTransaction(db, transaction);
495                             matchedTransactionsCount = 0;
496                             progress.setTotal(maxTransactionId);
497                         }
498
499                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
500                             (progress.getTotal() < transaction.getId()))
501                             progress.setTotal(transaction.getId());
502
503                         progress.setProgress(++processedTransactionCount);
504                         publishProgress(progress);
505                     }
506
507                     throwIfCancelled();
508                     profile.deleteNotPresentTransactions(db);
509                     throwIfCancelled();
510                     db.setTransactionSuccessful();
511                     profile.setLastUpdateStamp();
512                 }
513                 finally {
514                     db.endTransaction();
515                 }
516             }
517         }
518
519         return true;
520     }
521     @SuppressLint("DefaultLocale")
522     @Override
523     protected String doInBackground(Void... params) {
524         MobileLedgerProfile profile = Data.profile.get();
525         Data.backgroundTaskCount.incrementAndGet();
526         try {
527             if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
528                 return retrieveTransactionListLegacy(profile);
529             return null;
530         }
531         catch (MalformedURLException e) {
532             e.printStackTrace();
533             return "Invalid server URL";
534         }
535         catch (HTTPException e) {
536             e.printStackTrace();
537             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
538         }
539         catch (IOException e) {
540             e.printStackTrace();
541             return e.getLocalizedMessage();
542         }
543         catch (ParseException e) {
544             e.printStackTrace();
545             return "Network error";
546         }
547         catch (OperationCanceledException e) {
548             e.printStackTrace();
549             return "Operation cancelled";
550         }
551         finally {
552             Data.backgroundTaskCount.decrementAndGet();
553         }
554     }
555     private MainActivity getContext() {
556         return contextRef.get();
557     }
558     private void throwIfCancelled() {
559         if (isCancelled()) throw new OperationCanceledException(null);
560     }
561
562     private enum ParserState {
563         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
564         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
565     }
566
567     public class Progress {
568         public static final int INDETERMINATE = -1;
569         private int progress;
570         private int total;
571         Progress() {
572             this(INDETERMINATE, INDETERMINATE);
573         }
574         Progress(int progress, int total) {
575             this.progress = progress;
576             this.total = total;
577         }
578         public int getProgress() {
579             return progress;
580         }
581         protected void setProgress(int progress) {
582             this.progress = progress;
583         }
584         public int getTotal() {
585             return total;
586         }
587         protected void setTotal(int total) {
588             this.total = total;
589         }
590     }
591
592     private class TransactionParserException extends IllegalStateException {
593         TransactionParserException(String message) {
594             super(message);
595         }
596     }
597 }