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