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