]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
fix duplication af account amounts on refresh
[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
176                                         lastAccount.removeAmounts();
177                                     profile.storeAccount(db, lastAccount);
178
179                                     // make sure the parent account(s) are present,
180                                     // synthesising them if necessary
181                                     String parentName = lastAccount.getParentName();
182                                     if (parentName != null) {
183                                         Stack<String> toAppend = new Stack<>();
184                                         while (parentName != null) {
185                                             if (accountNames.containsKey(parentName)) break;
186                                             toAppend.push(parentName);
187                                             parentName =
188                                                     new LedgerAccount(parentName).getParentName();
189                                         }
190                                         while (!toAppend.isEmpty()) {
191                                             String aName = toAppend.pop();
192                                             LedgerAccount acc = new LedgerAccount(aName);
193                                             acc.setHiddenByStar(lastAccount.isHiddenByStar());
194                                             if (!onlyStarred || !acc.isHiddenByStar())
195                                                 accountList.add(acc);
196                                             L(String.format("gap-filling with %s", aName));
197                                             accountNames.put(aName, null);
198                                             profile.storeAccount(db, acc);
199                                         }
200                                     }
201
202                                     if (!onlyStarred || !lastAccount.isHiddenByStar())
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 = new LedgerAccount(parsedAccount.getAname());
400                         profile.storeAccount(db, acc);
401                         for (ParsedBalance b : parsedAccount.getAebalance()) {
402                             profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
403                                     b.getAquantity().asFloat());
404                         }
405
406                         accountList.add(acc);
407                     }
408                     throwIfCancelled();
409
410                     profile.deleteNotPresentAccounts(db);
411                     throwIfCancelled();
412                     db.setTransactionSuccessful();
413                     Data.accounts.set(accountList);
414                 }
415                 finally {
416                     db.endTransaction();
417                 }
418             }
419         }
420
421         return true;
422     }
423     private boolean retrieveTransactionList(MobileLedgerProfile profile)
424             throws IOException, ParseException, HTTPException {
425         Progress progress = new Progress();
426         int maxTransactionId = Progress.INDETERMINATE;
427
428         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
429         http.setAllowUserInteraction(false);
430         publishProgress(progress);
431         switch (http.getResponseCode()) {
432             case 200:
433                 break;
434             case 404:
435                 return false;
436             default:
437                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
438         }
439         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
440             try (InputStream resp = http.getInputStream()) {
441                 if (http.getResponseCode() != 200)
442                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
443                 throwIfCancelled();
444                 db.beginTransaction();
445                 try {
446                     profile.markTransactionsAsNotPresent(db);
447
448                     int matchedTransactionsCount = 0;
449                     TransactionListParser parser = new TransactionListParser(resp);
450
451                     int processedTransactionCount = 0;
452
453                     while (true) {
454                         throwIfCancelled();
455                         ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
456                         throwIfCancelled();
457                         if (parsedTransaction == null) break;
458                         LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
459                         if (transaction.existsInDb(db)) {
460                             profile.markTransactionAsPresent(db, transaction);
461                             matchedTransactionsCount++;
462
463                             if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
464                                 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
465                                 progress.setTotal(progress.getProgress());
466                                 publishProgress(progress);
467                                 db.setTransactionSuccessful();
468                                 profile.setLastUpdateStamp();
469                                 return true;
470                             }
471                         }
472                         else {
473                             profile.storeTransaction(db, transaction);
474                             matchedTransactionsCount = 0;
475                             progress.setTotal(maxTransactionId);
476                         }
477
478                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
479                             (progress.getTotal() < transaction.getId()))
480                             progress.setTotal(transaction.getId());
481
482                         progress.setProgress(++processedTransactionCount);
483                         publishProgress(progress);
484                     }
485
486                     throwIfCancelled();
487                     profile.deleteNotPresentTransactions(db);
488                     throwIfCancelled();
489                     db.setTransactionSuccessful();
490                     profile.setLastUpdateStamp();
491                 }
492                 finally {
493                     db.endTransaction();
494                 }
495             }
496         }
497
498         return true;
499     }
500     @SuppressLint("DefaultLocale")
501     @Override
502     protected String doInBackground(Void... params) {
503         MobileLedgerProfile profile = Data.profile.get();
504         Data.backgroundTaskCount.incrementAndGet();
505         try {
506             if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
507                 return retrieveTransactionListLegacy(profile);
508             return null;
509         }
510         catch (MalformedURLException e) {
511             e.printStackTrace();
512             return "Invalid server URL";
513         }
514         catch (HTTPException e) {
515             e.printStackTrace();
516             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
517         }
518         catch (IOException e) {
519             e.printStackTrace();
520             return e.getLocalizedMessage();
521         }
522         catch (ParseException e) {
523             e.printStackTrace();
524             return "Network error";
525         }
526         catch (OperationCanceledException e) {
527             e.printStackTrace();
528             return "Operation cancelled";
529         }
530         finally {
531             Data.backgroundTaskCount.decrementAndGet();
532         }
533     }
534     private MainActivity getContext() {
535         return contextRef.get();
536     }
537     private void throwIfCancelled() {
538         if (isCancelled()) throw new OperationCanceledException(null);
539     }
540
541     private enum ParserState {
542         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
543         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
544     }
545
546     public class Progress {
547         public static final int INDETERMINATE = -1;
548         private int progress;
549         private int total;
550         Progress() {
551             this(INDETERMINATE, INDETERMINATE);
552         }
553         Progress(int progress, int total) {
554             this.progress = progress;
555             this.total = total;
556         }
557         public int getProgress() {
558             return progress;
559         }
560         protected void setProgress(int progress) {
561             this.progress = progress;
562         }
563         public int getTotal() {
564             return total;
565         }
566         protected void setTotal(int total) {
567             this.total = total;
568         }
569     }
570
571     private class TransactionParserException extends IllegalStateException {
572         TransactionParserException(String message) {
573             super(message);
574         }
575     }
576 }