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