fallback to legacy HTML parsing
[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 {
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(db, 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(db, 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(db, 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,
288                                                     transaction);
289                                             progress.setTotal(progress.getProgress());
290                                             publishProgress(progress);
291                                             break LINES;
292                                         }
293                                     }
294                                     else {
295                                         profile.storeTransaction(db, transaction);
296                                         matchedTransactionsCount = 0;
297                                         progress.setTotal(maxTransactionId);
298                                     }
299
300                                     state = ParserState.EXPECTING_TRANSACTION;
301                                     L(String.format("transaction %s saved → expecting transaction",
302                                             transaction.getId()));
303                                     transaction.finishLoading();
304
305 // sounds like a good idea, but transaction-1 may not be the first one chronologically
306 // for example, when you add the initial seeding transaction after entering some others
307 //                                            if (transactionId == 1) {
308 //                                                L("This was the initial transaction. Terminating " +
309 //                                                  "parser");
310 //                                                break LINES;
311 //                                            }
312                                 }
313                                 else {
314                                     m = reTransactionDetails.matcher(line);
315                                     if (m.find()) {
316                                         String acc_name = m.group(1);
317                                         String amount = m.group(2);
318                                         String currency = m.group(3);
319                                         if (currency == null) currency = "";
320                                         amount = amount.replace(',', '.');
321                                         transaction.addAccount(
322                                                 new LedgerTransactionAccount(acc_name,
323                                                         Float.valueOf(amount), currency));
324                                         L(String.format("%d: %s = %s", transaction.getId(),
325                                                 acc_name, amount));
326                                     }
327                                     else throw new IllegalStateException(String.format(
328                                             "Can't parse transaction %d " + "details: %s",
329                                             transactionId, line));
330                                 }
331                                 break;
332                             default:
333                                 throw new RuntimeException(
334                                         String.format("Unknown parser updating %s", state.name()));
335                         }
336                     }
337
338                     throwIfCancelled();
339
340                     profile.deleteNotPresentTransactions(db);
341                     db.setTransactionSuccessful();
342
343                     profile.setLastUpdateStamp();
344
345                     return null;
346                 }
347                 finally {
348                     db.endTransaction();
349                 }
350             }
351         }
352     }
353     private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
354         db.execSQL("UPDATE transactions set keep=0 where profile=?",
355                 new String[]{profile.getUuid()});
356         db.execSQL("update account_values set keep=0 where profile=?;",
357                 new String[]{profile.getUuid()});
358         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
359     }
360     private boolean retrieveAccountList(MobileLedgerProfile profile)
361             throws IOException, HTTPException {
362         Progress progress = new Progress();
363
364         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
365         http.setAllowUserInteraction(false);
366         switch (http.getResponseCode()) {
367             case 200:
368                 break;
369             case 404:
370                 return false;
371             default:
372                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
373         }
374         publishProgress(progress);
375         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
376             try (InputStream resp = http.getInputStream()) {
377                 if (http.getResponseCode() != 200)
378                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
379
380                 db.beginTransaction();
381                 try {
382                     profile.markAccountsAsNotPresent(db);
383
384                     AccountListParser parser = new AccountListParser(resp);
385                     ArrayList<LedgerAccount> accountList = new ArrayList<>();
386
387                     while (true) {
388                         throwIfCancelled();
389                         ParsedLedgerAccount parsedAccount = parser.nextAccount();
390                         if (parsedAccount == null) break;
391
392                         LedgerAccount acc = new LedgerAccount(parsedAccount.getAname());
393                         profile.storeAccount(db, acc);
394                         for (ParsedBalance b : parsedAccount.getAebalance()) {
395                             profile.storeAccountValue(db, acc.getName(), b.getAcommodity(),
396                                     b.getAquantity().asFloat());
397                         }
398
399                         accountList.add(acc);
400                     }
401                     throwIfCancelled();
402
403                     profile.deleteNotPresentAccounts(db);
404                     throwIfCancelled();
405                     db.setTransactionSuccessful();
406                     Data.accounts.set(accountList);
407                 }
408                 finally {
409                     db.endTransaction();
410                 }
411             }
412         }
413
414         return true;
415     }
416     private boolean retrieveTransactionList(MobileLedgerProfile profile)
417             throws IOException, ParseException, HTTPException {
418         Progress progress = new Progress();
419         int maxTransactionId = Progress.INDETERMINATE;
420
421         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
422         http.setAllowUserInteraction(false);
423         publishProgress(progress);
424         switch (http.getResponseCode()) {
425             case 200:
426                 break;
427             case 404:
428                 return false;
429             default:
430                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
431         }
432         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
433             try (InputStream resp = http.getInputStream()) {
434                 if (http.getResponseCode() != 200)
435                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
436                 throwIfCancelled();
437                 db.beginTransaction();
438                 try {
439                     profile.markTransactionsAsNotPresent(db);
440
441                     int matchedTransactionsCount = 0;
442                     TransactionListParser parser = new TransactionListParser(resp);
443
444                     int processedTransactionCount = 0;
445
446                     while (true) {
447                         throwIfCancelled();
448                         ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
449                         throwIfCancelled();
450                         if (parsedTransaction == null) break;
451                         LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
452                         if (transaction.existsInDb(db)) {
453                             profile.markTransactionAsPresent(db, transaction);
454                             matchedTransactionsCount++;
455
456                             if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
457                                 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
458                                 progress.setTotal(progress.getProgress());
459                                 publishProgress(progress);
460                                 db.setTransactionSuccessful();
461                                 profile.setLastUpdateStamp();
462                                 return true;
463                             }
464                         }
465                         else {
466                             profile.storeTransaction(db, transaction);
467                             matchedTransactionsCount = 0;
468                             progress.setTotal(maxTransactionId);
469                         }
470
471                         progress.setProgress(++processedTransactionCount);
472                         publishProgress(progress);
473                     }
474
475                     throwIfCancelled();
476                     profile.deleteNotPresentTransactions(db);
477                     throwIfCancelled();
478                     db.setTransactionSuccessful();
479                     profile.setLastUpdateStamp();
480                 }
481                 finally {
482                     db.endTransaction();
483                 }
484             }
485         }
486
487         return true;
488     }
489     @SuppressLint("DefaultLocale")
490     @Override
491     protected String doInBackground(Void... params) {
492         MobileLedgerProfile profile = Data.profile.get();
493         Data.backgroundTaskCount.incrementAndGet();
494         try {
495             if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
496                 return retrieveTransactionListLegacy(profile);
497             return null;
498         }
499         catch (MalformedURLException e) {
500             e.printStackTrace();
501             return "Invalid server URL";
502         }
503         catch (HTTPException e) {
504             e.printStackTrace();
505             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
506         }
507         catch (IOException e) {
508             e.printStackTrace();
509             return "Parse error";
510         }
511         catch (ParseException e) {
512             e.printStackTrace();
513             return "Network error";
514         }
515         catch (OperationCanceledException e) {
516             e.printStackTrace();
517             return "Operation cancelled";
518         }
519         finally {
520             Data.backgroundTaskCount.decrementAndGet();
521         }
522     }
523     private MainActivity getContext() {
524         return contextRef.get();
525     }
526     private void throwIfCancelled() {
527         if (isCancelled()) throw new OperationCanceledException(null);
528     }
529
530     private enum ParserState {
531         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
532         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
533     }
534
535     public class Progress {
536         public static final int INDETERMINATE = -1;
537         private int progress;
538         private int total;
539         Progress() {
540             this(INDETERMINATE, INDETERMINATE);
541         }
542         Progress(int progress, int total) {
543             this.progress = progress;
544             this.total = total;
545         }
546         public int getProgress() {
547             return progress;
548         }
549         protected void setProgress(int progress) {
550             this.progress = progress;
551         }
552         public int getTotal() {
553             return total;
554         }
555         protected void setTotal(int total) {
556             this.total = total;
557         }
558     }
559
560     private class TransactionParserException extends IllegalStateException {
561         TransactionParserException(String message) {
562             super(message);
563         }
564     }
565 }