]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
preliminary implementation for retrieval of transactions/accounts using the JSON API
[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.Date;
53 import java.util.HashMap;
54 import java.util.Stack;
55 import java.util.regex.Matcher;
56 import java.util.regex.Pattern;
57
58
59 public class RetrieveTransactionsTask
60         extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
61     private static final int MATCHING_TRANSACTIONS_LIMIT = 50;
62     private static final Pattern reComment = Pattern.compile("^\\s*;");
63     private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
64                                                                       "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
65     private static final Pattern reTransactionDescription =
66             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
67     private static final Pattern reTransactionDetails =
68             Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
69     private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
70     private WeakReference<MainActivity> contextRef;
71     private int error;
72     // %3A is '='
73     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
74     private Pattern reAccountValue = Pattern.compile(
75             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
76     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
77         this.contextRef = contextRef;
78     }
79     private static void L(String msg) {
80         //Log.d("transaction-parser", msg);
81     }
82     @Override
83     protected void onProgressUpdate(Progress... values) {
84         super.onProgressUpdate(values);
85         MainActivity context = getContext();
86         if (context == null) return;
87         context.onRetrieveProgress(values[0]);
88     }
89     @Override
90     protected void onPreExecute() {
91         super.onPreExecute();
92         MainActivity context = getContext();
93         if (context == null) return;
94         context.onRetrieveStart();
95     }
96     @Override
97     protected void onPostExecute(String error) {
98         super.onPostExecute(error);
99         MainActivity context = getContext();
100         if (context == null) return;
101         context.onRetrieveDone(error);
102     }
103     @Override
104     protected void onCancelled() {
105         super.onCancelled();
106         MainActivity context = getContext();
107         if (context == null) return;
108         context.onRetrieveDone(null);
109     }
110     private String retrieveTransactionListLegacy(MobileLedgerProfile profile)
111             throws IOException, ParseException {
112         Progress progress = new Progress();
113         int maxTransactionId = Progress.INDETERMINATE;
114         ArrayList<LedgerAccount> accountList = new ArrayList<>();
115         HashMap<String, Void> accountNames = new HashMap<>();
116         LedgerAccount lastAccount = null;
117         boolean onlyStarred = Data.optShowOnlyStarred.get();
118
119         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
120         http.setAllowUserInteraction(false);
121         publishProgress(progress);
122         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
123             try (InputStream resp = http.getInputStream()) {
124                 if (http.getResponseCode() != 200)
125                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
126                 db.beginTransaction();
127                 try {
128                     prepareDbForRetrieval(db, profile);
129
130                     int matchedTransactionsCount = 0;
131
132
133                     ParserState state = ParserState.EXPECTING_ACCOUNT;
134                     String line;
135                     BufferedReader buf =
136                             new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
137
138                     int processedTransactionCount = 0;
139                     int transactionId = 0;
140                     LedgerTransaction transaction = null;
141                     LINES:
142                     while ((line = buf.readLine()) != null) {
143                         throwIfCancelled();
144                         Matcher m;
145                         m = reComment.matcher(line);
146                         if (m.find()) {
147                             // TODO: comments are ignored for now
148                             Log.v("transaction-parser", "Ignoring comment");
149                             continue;
150                         }
151                         //L(String.format("State is %d", updating));
152                         switch (state) {
153                             case EXPECTING_ACCOUNT:
154                                 if (line.equals("<h2>General Journal</h2>")) {
155                                     state = ParserState.EXPECTING_TRANSACTION;
156                                     L("→ expecting transaction");
157                                     Data.accounts.set(accountList);
158                                     continue;
159                                 }
160                                 m = reAccountName.matcher(line);
161                                 if (m.find()) {
162                                     String acct_encoded = m.group(1);
163                                     String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
164                                     acct_name = acct_name.replace("\"", "");
165                                     L(String.format("found account: %s", acct_name));
166
167                                     lastAccount = profile.loadAccount(acct_name);
168                                     if (lastAccount == null) {
169                                         lastAccount = new LedgerAccount(acct_name);
170                                         profile.storeAccount(lastAccount);
171                                     }
172
173                                     // make sure the parent account(s) are present,
174                                     // synthesising them if necessary
175                                     String parentName = lastAccount.getParentName();
176                                     if (parentName != null) {
177                                         Stack<String> toAppend = new Stack<>();
178                                         while (parentName != null) {
179                                             if (accountNames.containsKey(parentName)) break;
180                                             toAppend.push(parentName);
181                                             parentName =
182                                                     new LedgerAccount(parentName).getParentName();
183                                         }
184                                         while (!toAppend.isEmpty()) {
185                                             String aName = toAppend.pop();
186                                             LedgerAccount acc = new LedgerAccount(aName);
187                                             acc.setHidden(lastAccount.isHidden());
188                                             if (!onlyStarred || !acc.isHidden())
189                                                 accountList.add(acc);
190                                             L(String.format("gap-filling with %s", aName));
191                                             accountNames.put(aName, null);
192                                             profile.storeAccount(acc);
193                                         }
194                                     }
195
196                                     if (!onlyStarred || !lastAccount.isHidden())
197                                         accountList.add(lastAccount);
198                                     accountNames.put(acct_name, null);
199
200                                     state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
201                                     L("→ expecting account amount");
202                                 }
203                                 break;
204
205                             case EXPECTING_ACCOUNT_AMOUNT:
206                                 m = reAccountValue.matcher(line);
207                                 boolean match_found = false;
208                                 while (m.find()) {
209                                     throwIfCancelled();
210
211                                     match_found = true;
212                                     String value = m.group(1);
213                                     String currency = m.group(2);
214                                     if (currency == null) currency = "";
215                                     value = value.replace(',', '.');
216                                     L("curr=" + currency + ", value=" + value);
217                                     profile.storeAccountValue(lastAccount.getName(), currency,
218                                             Float.valueOf(value));
219                                     lastAccount.addAmount(Float.parseFloat(value), currency);
220                                 }
221
222                                 if (match_found) {
223                                     state = ParserState.EXPECTING_ACCOUNT;
224                                     L("→ expecting account");
225                                 }
226
227                                 break;
228
229                             case EXPECTING_TRANSACTION:
230                                 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
231                                 m = reTransactionStart.matcher(line);
232                                 if (m.find()) {
233                                     transactionId = Integer.valueOf(m.group(1));
234                                     state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
235                                     L(String.format("found transaction %d → expecting description",
236                                             transactionId));
237                                     progress.setProgress(++processedTransactionCount);
238                                     if (maxTransactionId < transactionId)
239                                         maxTransactionId = transactionId;
240                                     if ((progress.getTotal() == Progress.INDETERMINATE) ||
241                                         (progress.getTotal() < transactionId))
242                                         progress.setTotal(transactionId);
243                                     publishProgress(progress);
244                                 }
245                                 m = reEnd.matcher(line);
246                                 if (m.find()) {
247                                     L("--- transaction value complete ---");
248                                     break LINES;
249                                 }
250                                 break;
251
252                             case EXPECTING_TRANSACTION_DESCRIPTION:
253                                 if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
254                                 m = reTransactionDescription.matcher(line);
255                                 if (m.find()) {
256                                     if (transactionId == 0) throw new TransactionParserException(
257                                             "Transaction Id is 0 while expecting " + "description");
258
259                                     String date = m.group(1);
260                                     try {
261                                         int equalsIndex = date.indexOf('=');
262                                         if (equalsIndex >= 0)
263                                             date = date.substring(equalsIndex + 1);
264                                         transaction = new LedgerTransaction(transactionId, date,
265                                                 m.group(2));
266                                     }
267                                     catch (ParseException e) {
268                                         e.printStackTrace();
269                                         return String.format("Error parsing date '%s'", date);
270                                     }
271                                     state = ParserState.EXPECTING_TRANSACTION_DETAILS;
272                                     L(String.format("transaction %d created for %s (%s) →" +
273                                                     " expecting details", transactionId, date,
274                                             m.group(2)));
275                                 }
276                                 break;
277
278                             case EXPECTING_TRANSACTION_DETAILS:
279                                 if (line.isEmpty()) {
280                                     // transaction data collected
281                                     if (transaction.existsInDb(db)) {
282                                         profile.markTransactionAsPresent(db, transaction);
283                                         matchedTransactionsCount++;
284
285                                         if (matchedTransactionsCount ==
286                                             MATCHING_TRANSACTIONS_LIMIT)
287                                         {
288                                             profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
289                                             progress.setTotal(progress.getProgress());
290                                             publishProgress(progress);
291                                             break LINES;
292                                         }
293                                     }
294                                     else {
295                                         profile.storeTransaction(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                     Log.d("db", "Updating transaction value stamp");
344                     Date now = new Date();
345                     profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
346                     Data.lastUpdateDate.set(now);
347
348                     return null;
349                 }
350                 finally {
351                     db.endTransaction();
352                 }
353             }
354         }
355     }
356     private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
357         db.execSQL("UPDATE transactions set keep=0 where profile=?",
358                 new String[]{profile.getUuid()});
359         db.execSQL("update account_values set keep=0 where profile=?;",
360                 new String[]{profile.getUuid()});
361         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
362     }
363     private boolean retrieveAccountList(MobileLedgerProfile profile) throws IOException {
364         Progress progress = new Progress();
365
366         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
367         http.setAllowUserInteraction(false);
368         publishProgress(progress);
369         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
370             try (InputStream resp = http.getInputStream()) {
371                 if (http.getResponseCode() != 200)
372                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
373
374                 db.beginTransaction();
375                 try {
376                     profile.markAccountsAsNotPresent(db);
377
378                     AccountListParser parser = new AccountListParser(resp);
379
380                     while (true) {
381                         ParsedLedgerAccount parsedAccount = parser.nextAccount();
382                         if (parsedAccount == null) break;
383
384                         LedgerAccount acc = new LedgerAccount(parsedAccount.getAname());
385                         profile.storeAccount(acc);
386                         for (ParsedBalance b : parsedAccount.getAebalance()) {
387                             profile.storeAccountValue(acc.getName(), b.getAcommodity(),
388                                     b.getAquantity().asFloat());
389                         }
390                     }
391
392                     profile.deleteNotPresentAccounts(db);
393                     db.setTransactionSuccessful();
394                 }
395                 finally {
396                     db.endTransaction();
397                 }
398             }
399         }
400
401         return true;
402     }
403     private boolean retrieveTransactionList(MobileLedgerProfile profile)
404             throws IOException, ParseException {
405         Progress progress = new Progress();
406         int maxTransactionId = Progress.INDETERMINATE;
407
408         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
409         http.setAllowUserInteraction(false);
410         publishProgress(progress);
411         try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
412             try (InputStream resp = http.getInputStream()) {
413                 if (http.getResponseCode() != 200)
414                     throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
415                 db.beginTransaction();
416                 try {
417                     profile.markTransactionsAsNotPresent(db);
418
419                     int matchedTransactionsCount = 0;
420                     TransactionListParser parser = new TransactionListParser(resp);
421
422                     int processedTransactionCount = 0;
423
424                     while (true) {
425                         ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
426                         if (parsedTransaction == null) break;
427                         LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
428                         if (transaction.existsInDb(db)) {
429                             profile.markTransactionAsPresent(db, transaction);
430                             matchedTransactionsCount++;
431
432                             if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
433                                 profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
434                                 progress.setTotal(progress.getProgress());
435                                 publishProgress(progress);
436                                 db.setTransactionSuccessful();
437                                 return true;
438                             }
439                         }
440                         else {
441                             profile.storeTransaction(transaction);
442                             matchedTransactionsCount = 0;
443                             progress.setTotal(maxTransactionId);
444                         }
445
446                         progress.setProgress(++processedTransactionCount);
447                         publishProgress(progress);
448                     }
449
450                     profile.deleteNotPresentTransactions(db);
451                     db.setTransactionSuccessful();
452                 }
453                 finally {
454                     db.endTransaction();
455                 }
456             }
457         }
458
459         return true;
460     }
461     @SuppressLint("DefaultLocale")
462     @Override
463     protected String doInBackground(Void... params) {
464         MobileLedgerProfile profile = Data.profile.get();
465         Data.backgroundTaskCount.incrementAndGet();
466         try {
467             if (!retrieveAccountList(profile) || !retrieveTransactionList(profile))
468                 return retrieveTransactionListLegacy(profile);
469             return null;
470         }
471         catch (MalformedURLException e) {
472             e.printStackTrace();
473             return "Invalid server URL";
474         }
475         catch (FileNotFoundException e) {
476             e.printStackTrace();
477             return "Invalid user name or password";
478         }
479         catch (IOException e) {
480             e.printStackTrace();
481             return "Network error";
482         }
483         catch (ParseException e) {
484             e.printStackTrace();
485             return "Network error";
486         }
487         catch (OperationCanceledException e) {
488             e.printStackTrace();
489             return "Operation cancelled";
490         }
491         finally {
492             Data.backgroundTaskCount.decrementAndGet();
493         }
494     }
495     private MainActivity getContext() {
496         return contextRef.get();
497     }
498     private void throwIfCancelled() {
499         if (isCancelled()) throw new OperationCanceledException(null);
500     }
501
502     private enum ParserState {
503         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
504         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
505     }
506
507     public class Progress {
508         public static final int INDETERMINATE = -1;
509         private int progress;
510         private int total;
511         Progress() {
512             this(INDETERMINATE, INDETERMINATE);
513         }
514         Progress(int progress, int total) {
515             this.progress = progress;
516             this.total = total;
517         }
518         public int getProgress() {
519             return progress;
520         }
521         protected void setProgress(int progress) {
522             this.progress = progress;
523         }
524         public int getTotal() {
525             return total;
526         }
527         protected void setTotal(int total) {
528             this.total = total;
529         }
530     }
531
532     private class TransactionParserException extends IllegalStateException {
533         TransactionParserException(String message) {
534             super(message);
535         }
536     }
537 }