]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
refresh profile list when the backend data changes
[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;
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.getWritableDatabase()) {
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                                     Data.accounts.set(accountList);
163                                     continue;
164                                 }
165                                 m = reAccountName.matcher(line);
166                                 if (m.find()) {
167                                     String acct_encoded = m.group(1);
168                                     String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
169                                     acct_name = acct_name.replace("\"", "");
170                                     L(String.format("found account: %s", acct_name));
171
172                                     lastAccount = profile.tryLoadAccount(db, acct_name);
173                                     if (lastAccount == null)
174                                         lastAccount = new LedgerAccount(acct_name);
175                                     else lastAccount.removeAmounts();
176                                     profile.storeAccount(db, lastAccount);
177
178                                     // make sure the parent account(s) are present,
179                                     // synthesising them if necessary
180                                     String parentName = lastAccount.getParentName();
181                                     if (parentName != null) {
182                                         Stack<String> toAppend = new Stack<>();
183                                         while (parentName != null) {
184                                             if (accountNames.containsKey(parentName)) break;
185                                             toAppend.push(parentName);
186                                             parentName =
187                                                     new LedgerAccount(parentName).getParentName();
188                                         }
189                                         while (!toAppend.isEmpty()) {
190                                             String aName = toAppend.pop();
191                                             LedgerAccount acc = new LedgerAccount(aName);
192                                             acc.setHiddenByStar(lastAccount.isHiddenByStar());
193                                             if ((!onlyStarred || !acc.isHiddenByStar()) &&
194                                                 acc.isVisible(accountList)) accountList.add(acc);
195                                             L(String.format("gap-filling with %s", aName));
196                                             accountNames.put(aName, null);
197                                             profile.storeAccount(db, acc);
198                                         }
199                                     }
200
201                                     if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
202                                         lastAccount.isVisible(accountList))
203                                         accountList.add(lastAccount);
204                                     accountNames.put(acct_name, null);
205
206                                     state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
207                                     L("→ expecting account amount");
208                                 }
209                                 break;
210
211                             case EXPECTING_ACCOUNT_AMOUNT:
212                                 m = reAccountValue.matcher(line);
213                                 boolean match_found = false;
214                                 while (m.find()) {
215                                     throwIfCancelled();
216
217                                     match_found = true;
218                                     String value = m.group(1);
219                                     String currency = m.group(2);
220                                     if (currency == null) currency = "";
221                                     value = value.replace(',', '.');
222                                     L("curr=" + currency + ", value=" + value);
223                                     profile.storeAccountValue(db, lastAccount.getName(), currency,
224                                             Float.valueOf(value));
225                                     lastAccount.addAmount(Float.parseFloat(value), currency);
226                                 }
227
228                                 if (match_found) {
229                                     state = ParserState.EXPECTING_ACCOUNT;
230                                     L("→ expecting account");
231                                 }
232
233                                 break;
234
235                             case EXPECTING_TRANSACTION:
236                                 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
237                                 m = reTransactionStart.matcher(line);
238                                 if (m.find()) {
239                                     transactionId = Integer.valueOf(m.group(1));
240                                     state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
241                                     L(String.format("found transaction %d → expecting description",
242                                             transactionId));
243                                     progress.setProgress(++processedTransactionCount);
244                                     if (maxTransactionId < transactionId)
245                                         maxTransactionId = transactionId;
246                                     if ((progress.getTotal() == Progress.INDETERMINATE) ||
247                                         (progress.getTotal() < transactionId))
248                                         progress.setTotal(transactionId);
249                                     publishProgress(progress);
250                                 }
251                                 m = reEnd.matcher(line);
252                                 if (m.find()) {
253                                     L("--- transaction value complete ---");
254                                     break LINES;
255                                 }
256                                 break;
257
258                             case EXPECTING_TRANSACTION_DESCRIPTION:
259                                 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
260                                 m = reTransactionDescription.matcher(line);
261                                 if (m.find()) {
262                                     if (transactionId == 0) throw new TransactionParserException(
263                                             "Transaction Id is 0 while expecting " + "description");
264
265                                     String date = m.group(1);
266                                     try {
267                                         int equalsIndex = date.indexOf('=');
268                                         if (equalsIndex >= 0)
269                                             date = date.substring(equalsIndex + 1);
270                                         transaction = new LedgerTransaction(transactionId, date,
271                                                 m.group(2));
272                                     }
273                                     catch (ParseException e) {
274                                         e.printStackTrace();
275                                         return String.format("Error parsing date '%s'", date);
276                                     }
277                                     state = ParserState.EXPECTING_TRANSACTION_DETAILS;
278                                     L(String.format("transaction %d created for %s (%s) →" +
279                                                     " expecting details", transactionId, date,
280                                             m.group(2)));
281                                 }
282                                 break;
283
284                             case EXPECTING_TRANSACTION_DETAILS:
285                                 if (line.isEmpty()) {
286                                     // transaction data collected
287                                     if (transaction.existsInDb(db)) {
288                                         profile.markTransactionAsPresent(db, transaction);
289                                         matchedTransactionsCount++;
290
291                                         if (matchedTransactionsCount ==
292                                             MATCHING_TRANSACTIONS_LIMIT)
293                                         {
294                                             profile.markTransactionsBeforeTransactionAsPresent(db,
295                                                     transaction);
296                                             progress.setTotal(progress.getProgress());
297                                             publishProgress(progress);
298                                             break LINES;
299                                         }
300                                     }
301                                     else {
302                                         profile.storeTransaction(db, transaction);
303                                         matchedTransactionsCount = 0;
304                                         progress.setTotal(maxTransactionId);
305                                     }
306
307                                     state = ParserState.EXPECTING_TRANSACTION;
308                                     L(String.format("transaction %s saved → expecting transaction",
309                                             transaction.getId()));
310                                     transaction.finishLoading();
311
312 // sounds like a good idea, but transaction-1 may not be the first one chronologically
313 // for example, when you add the initial seeding transaction after entering some others
314 //                                            if (transactionId == 1) {
315 //                                                L("This was the initial transaction. Terminating " +
316 //                                                  "parser");
317 //                                                break LINES;
318 //                                            }
319                                 }
320                                 else {
321                                     m = reTransactionDetails.matcher(line);
322                                     if (m.find()) {
323                                         String acc_name = m.group(1);
324                                         String amount = m.group(2);
325                                         String currency = m.group(3);
326                                         if (currency == null) currency = "";
327                                         amount = amount.replace(',', '.');
328                                         transaction.addAccount(
329                                                 new LedgerTransactionAccount(acc_name,
330                                                         Float.valueOf(amount), currency));
331                                         L(String.format("%d: %s = %s", transaction.getId(),
332                                                 acc_name, amount));
333                                     }
334                                     else throw new IllegalStateException(String.format(
335                                             "Can't parse transaction %d " + "details: %s",
336                                             transactionId, line));
337                                 }
338                                 break;
339                             default:
340                                 throw new RuntimeException(
341                                         String.format("Unknown parser updating %s", state.name()));
342                         }
343                     }
344
345                     throwIfCancelled();
346
347                     profile.deleteNotPresentTransactions(db);
348                     db.setTransactionSuccessful();
349
350                     profile.setLastUpdateStamp();
351
352                     return null;
353                 }
354                 finally {
355                     db.endTransaction();
356                 }
357             }
358         }
359     }
360     private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
361         db.execSQL("UPDATE transactions set keep=0 where profile=?",
362                 new String[]{profile.getUuid()});
363         db.execSQL("update account_values set keep=0 where profile=?;",
364                 new String[]{profile.getUuid()});
365         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
366     }
367     private boolean retrieveAccountList(MobileLedgerProfile profile)
368             throws IOException, HTTPException {
369         Progress progress = new Progress();
370
371         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
372         http.setAllowUserInteraction(false);
373         switch (http.getResponseCode()) {
374             case 200:
375                 break;
376             case 404:
377                 return false;
378             default:
379                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
380         }
381         publishProgress(progress);
382         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
383             try (InputStream resp = http.getInputStream()) {
384                 if (http.getResponseCode() != 200)
385                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
386
387                 db.beginTransaction();
388                 try {
389                     profile.markAccountsAsNotPresent(db);
390
391                     AccountListParser parser = new AccountListParser(resp);
392                     ArrayList<LedgerAccount> accountList = new ArrayList<>();
393
394                     while (true) {
395                         throwIfCancelled();
396                         ParsedLedgerAccount parsedAccount = parser.nextAccount();
397                         if (parsedAccount == null) break;
398
399                         LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
400                         if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
401                         else acc.removeAmounts();
402
403                         profile.storeAccount(db, acc);
404                         for (ParsedBalance b : parsedAccount.getAebalance()) {
405                             profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
406                                     b.getAquantity().asFloat());
407                         }
408
409                         if (acc.isVisible(accountList)) accountList.add(acc);
410                     }
411                     throwIfCancelled();
412
413                     profile.deleteNotPresentAccounts(db);
414                     throwIfCancelled();
415                     db.setTransactionSuccessful();
416                     Data.accounts.set(accountList);
417                 }
418                 finally {
419                     db.endTransaction();
420                 }
421             }
422         }
423
424         return true;
425     }
426     private boolean retrieveTransactionList(MobileLedgerProfile profile)
427             throws IOException, ParseException, HTTPException {
428         Progress progress = new Progress();
429         int maxTransactionId = Progress.INDETERMINATE;
430
431         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
432         http.setAllowUserInteraction(false);
433         publishProgress(progress);
434         switch (http.getResponseCode()) {
435             case 200:
436                 break;
437             case 404:
438                 return false;
439             default:
440                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
441         }
442         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
443             try (InputStream resp = http.getInputStream()) {
444                 if (http.getResponseCode() != 200)
445                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
446                 throwIfCancelled();
447                 db.beginTransaction();
448                 try {
449                     profile.markTransactionsAsNotPresent(db);
450
451                     int matchedTransactionsCount = 0;
452                     TransactionListParser parser = new TransactionListParser(resp);
453
454                     int processedTransactionCount = 0;
455
456                     while (true) {
457                         throwIfCancelled();
458                         ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
459                         throwIfCancelled();
460                         if (parsedTransaction == null) break;
461                         LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
462                         if (transaction.existsInDb(db)) {
463                             profile.markTransactionAsPresent(db, transaction);
464                             matchedTransactionsCount++;
465
466                             if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
467                                 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
468                                 progress.setTotal(progress.getProgress());
469                                 publishProgress(progress);
470                                 db.setTransactionSuccessful();
471                                 profile.setLastUpdateStamp();
472                                 return true;
473                             }
474                         }
475                         else {
476                             profile.storeTransaction(db, transaction);
477                             matchedTransactionsCount = 0;
478                             progress.setTotal(maxTransactionId);
479                         }
480
481                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
482                             (progress.getTotal() < transaction.getId()))
483                             progress.setTotal(transaction.getId());
484
485                         progress.setProgress(++processedTransactionCount);
486                         publishProgress(progress);
487                     }
488
489                     throwIfCancelled();
490                     profile.deleteNotPresentTransactions(db);
491                     throwIfCancelled();
492                     db.setTransactionSuccessful();
493                     profile.setLastUpdateStamp();
494                 }
495                 finally {
496                     db.endTransaction();
497                 }
498             }
499         }
500
501         return true;
502     }
503     @SuppressLint("DefaultLocale")
504     @Override
505     protected String doInBackground(Void... params) {
506         MobileLedgerProfile profile = Data.profile.get();
507         Data.backgroundTaskCount.incrementAndGet();
508         try {
509             if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
510                 return retrieveTransactionListLegacy(profile);
511             return null;
512         }
513         catch (MalformedURLException e) {
514             e.printStackTrace();
515             return "Invalid server URL";
516         }
517         catch (HTTPException e) {
518             e.printStackTrace();
519             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
520         }
521         catch (IOException e) {
522             e.printStackTrace();
523             return e.getLocalizedMessage();
524         }
525         catch (ParseException e) {
526             e.printStackTrace();
527             return "Network error";
528         }
529         catch (OperationCanceledException e) {
530             e.printStackTrace();
531             return "Operation cancelled";
532         }
533         finally {
534             Data.backgroundTaskCount.decrementAndGet();
535         }
536     }
537     private MainActivity getContext() {
538         return contextRef.get();
539     }
540     private void throwIfCancelled() {
541         if (isCancelled()) throw new OperationCanceledException(null);
542     }
543
544     private enum ParserState {
545         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
546         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
547     }
548
549     public class Progress {
550         public static final int INDETERMINATE = -1;
551         private int progress;
552         private int total;
553         Progress() {
554             this(INDETERMINATE, INDETERMINATE);
555         }
556         Progress(int progress, int total) {
557             this.progress = progress;
558             this.total = total;
559         }
560         public int getProgress() {
561             return progress;
562         }
563         protected void setProgress(int progress) {
564             this.progress = progress;
565         }
566         public int getTotal() {
567             return total;
568         }
569         protected void setTotal(int total) {
570             this.total = total;
571         }
572     }
573
574     private class TransactionParserException extends IllegalStateException {
575         TransactionParserException(String message) {
576             super(message);
577         }
578     }
579 }