]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
handle date parsing errors, handle real=fake dates
[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 Mobile-Ledger.
4  * Mobile-Ledger 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  * Mobile-Ledger 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 Mobile-Ledger. 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.model.Data;
27 import net.ktnx.mobileledger.model.LedgerAccount;
28 import net.ktnx.mobileledger.model.LedgerTransaction;
29 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
30 import net.ktnx.mobileledger.model.MobileLedgerProfile;
31 import net.ktnx.mobileledger.ui.activity.MainActivity;
32 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
33 import net.ktnx.mobileledger.utils.MLDB;
34 import net.ktnx.mobileledger.utils.NetworkUtil;
35
36 import java.io.BufferedReader;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.InputStreamReader;
41 import java.lang.ref.WeakReference;
42 import java.net.HttpURLConnection;
43 import java.net.MalformedURLException;
44 import java.net.URLDecoder;
45 import java.text.ParseException;
46 import java.util.ArrayList;
47 import java.util.Date;
48 import java.util.HashMap;
49 import java.util.Stack;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52
53
54 public class RetrieveTransactionsTask
55         extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
56     private static final int MATCHING_TRANSACTIONS_LIMIT = 50;
57     private static final Pattern reComment = Pattern.compile("^\\s*;");
58     private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
59                                                                       "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
60     private static final Pattern reTransactionDescription =
61             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
62     private static final Pattern reTransactionDetails =
63             Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
64     private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
65     private WeakReference<MainActivity> contextRef;
66     private int error;
67     // %3A is '='
68     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
69     private Pattern reAccountValue = Pattern.compile(
70             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
71     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
72         this.contextRef = contextRef;
73     }
74     private static void L(String msg) {
75         Log.d("transaction-parser", msg);
76     }
77     @Override
78     protected void onProgressUpdate(Progress... values) {
79         super.onProgressUpdate(values);
80         MainActivity context = getContext();
81         if (context == null) return;
82         context.onRetrieveProgress(values[0]);
83     }
84     @Override
85     protected void onPreExecute() {
86         super.onPreExecute();
87         MainActivity context = getContext();
88         if (context == null) return;
89         context.onRetrieveStart();
90     }
91     @Override
92     protected void onPostExecute(String error) {
93         super.onPostExecute(error);
94         MainActivity context = getContext();
95         if (context == null) return;
96         context.onRetrieveDone(error);
97     }
98     @Override
99     protected void onCancelled() {
100         super.onCancelled();
101         MainActivity context = getContext();
102         if (context == null) return;
103         context.onRetrieveDone(null);
104     }
105     @SuppressLint("DefaultLocale")
106     @Override
107     protected String doInBackground(Void... params) {
108         MobileLedgerProfile profile = Data.profile.get();
109         Progress progress = new Progress();
110         int maxTransactionId = Progress.INDETERMINATE;
111         ArrayList<LedgerAccount> accountList = new ArrayList<>();
112         HashMap<String, Void> accountNames = new HashMap<>();
113         LedgerAccount lastAccount = null;
114         boolean onlyStarred = Data.optShowOnlyStarred.get();
115         Data.backgroundTaskCount.incrementAndGet();
116         try {
117             HttpURLConnection http = NetworkUtil.prepareConnection("journal");
118             http.setAllowUserInteraction(false);
119             publishProgress(progress);
120             MainActivity ctx = getContext();
121             if (ctx == null) return null;
122             try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
123                 try (InputStream resp = http.getInputStream()) {
124                     if (http.getResponseCode() != 200) throw new IOException(
125                             String.format("HTTP error %d", http.getResponseCode()));
126                     db.beginTransaction();
127                     try {
128                         db.execSQL("UPDATE transactions set keep=0");
129                         db.execSQL("update account_values set keep=0;");
130                         db.execSQL("update accounts set keep=0;");
131
132                         ParserState state = ParserState.EXPECTING_ACCOUNT;
133                         String line;
134                         BufferedReader buf =
135                                 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
136
137                         int processedTransactionCount = 0;
138                         int transactionId = 0;
139                         int matchedTransactionsCount = 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 = new LedgerAccount(parentName)
182                                                         .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(
236                                                 "found transaction %d → expecting description",
237                                                 transactionId));
238                                         progress.setProgress(++processedTransactionCount);
239                                         if (maxTransactionId < transactionId)
240                                             maxTransactionId = transactionId;
241                                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
242                                             (progress.getTotal() < transactionId))
243                                             progress.setTotal(transactionId);
244                                         publishProgress(progress);
245                                     }
246                                     m = reEnd.matcher(line);
247                                     if (m.find()) {
248                                         L("--- transaction value complete ---");
249                                         break LINES;
250                                     }
251                                     break;
252
253                                 case EXPECTING_TRANSACTION_DESCRIPTION:
254                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
255                                     m = reTransactionDescription.matcher(line);
256                                     if (m.find()) {
257                                         if (transactionId == 0)
258                                             throw new TransactionParserException(
259                                                     "Transaction Id is 0 while expecting " +
260                                                     "description");
261
262                                         String date = m.group(1);
263                                         try {
264                                             int equalsIndex = date.indexOf('=');
265                                             if (equalsIndex >= 0)
266                                                 date = date.substring(equalsIndex + 1);
267                                             transaction = new LedgerTransaction(transactionId, date,
268                                                     m.group(2));
269                                         }
270                                         catch (ParseException e) {
271                                             e.printStackTrace();
272                                             return String.format("Error parsing date '%s'", date);
273                                         }
274                                         state = ParserState.EXPECTING_TRANSACTION_DETAILS;
275                                         L(String.format("transaction %d created for %s (%s) →" +
276                                                         " expecting details", transactionId, date,
277                                                 m.group(2)));
278                                     }
279                                     break;
280
281                                 case EXPECTING_TRANSACTION_DETAILS:
282                                     if (line.isEmpty()) {
283                                         // transaction data collected
284                                         if (transaction.existsInDb(db)) {
285                                             db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
286                                                        "profile = ? and id=?",
287                                                     new Object[]{profile.getUuid(),
288                                                                  transaction.getId()
289                                                     });
290                                             matchedTransactionsCount++;
291
292                                             if (matchedTransactionsCount ==
293                                                 MATCHING_TRANSACTIONS_LIMIT)
294                                             {
295                                                 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
296                                                            "profile = ? and id < ?",
297                                                         new Object[]{profile.getUuid(),
298                                                                      transaction.getId()
299                                                         });
300                                                 progress.setTotal(progress.getProgress());
301                                                 publishProgress(progress);
302                                                 break LINES;
303                                             }
304                                         }
305                                         else {
306                                             profile.storeTransaction(transaction);
307                                             matchedTransactionsCount = 0;
308                                             progress.setTotal(maxTransactionId);
309                                         }
310
311                                         state = ParserState.EXPECTING_TRANSACTION;
312                                         L(String.format(
313                                                 "transaction %s saved → expecting transaction",
314                                                 transaction.getId()));
315                                         transaction.finishLoading();
316
317 // sounds like a good idea, but transaction-1 may not be the first one chronologically
318 // for example, when you add the initial seeding transaction after entering some others
319 //                                            if (transactionId == 1) {
320 //                                                L("This was the initial transaction. Terminating " +
321 //                                                  "parser");
322 //                                                break LINES;
323 //                                            }
324                                     }
325                                     else {
326                                         m = reTransactionDetails.matcher(line);
327                                         if (m.find()) {
328                                             String acc_name = m.group(1);
329                                             String amount = m.group(2);
330                                             String currency = m.group(3);
331                                             if (currency == null) currency = "";
332                                             amount = amount.replace(',', '.');
333                                             transaction.addAccount(
334                                                     new LedgerTransactionAccount(acc_name,
335                                                             Float.valueOf(amount), currency));
336                                             L(String.format("%d: %s = %s", transaction.getId(),
337                                                     acc_name, amount));
338                                         }
339                                         else throw new IllegalStateException(String.format(
340                                                 "Can't parse transaction %d " + "details: %s",
341                                                 transactionId, line));
342                                     }
343                                     break;
344                                 default:
345                                     throw new RuntimeException(
346                                             String.format("Unknown parser updating %s",
347                                                     state.name()));
348                             }
349                         }
350
351                         throwIfCancelled();
352
353                         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
354                                 new String[]{profile.getUuid()});
355                         db.setTransactionSuccessful();
356
357                         Log.d("db", "Updating transaction value stamp");
358                         Date now = new Date();
359                         profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
360                         Data.lastUpdateDate.set(now);
361                         TransactionListViewModel.scheduleTransactionListReload();
362
363                         return null;
364                     }
365                     finally {
366                         db.endTransaction();
367                     }
368                 }
369             }
370         }
371         catch (MalformedURLException e) {
372             e.printStackTrace();
373             return "Invalid server URL";
374         }
375         catch (FileNotFoundException e) {
376             e.printStackTrace();
377             return "Invalid user name or password";
378         }
379         catch (IOException e) {
380             e.printStackTrace();
381             return "Network error";
382         }
383         catch (OperationCanceledException e) {
384             e.printStackTrace();
385             return "Operation cancelled";
386         }
387         finally {
388             Data.backgroundTaskCount.decrementAndGet();
389         }
390     }
391     private MainActivity getContext() {
392         return contextRef.get();
393     }
394     private void throwIfCancelled() {
395         if (isCancelled()) throw new OperationCanceledException(null);
396     }
397
398     private enum ParserState {
399         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
400         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
401     }
402
403     public class Progress {
404         public static final int INDETERMINATE = -1;
405         private int progress;
406         private int total;
407         Progress() {
408             this(INDETERMINATE, INDETERMINATE);
409         }
410         Progress(int progress, int total) {
411             this.progress = progress;
412             this.total = total;
413         }
414         public int getProgress() {
415             return progress;
416         }
417         protected void setProgress(int progress) {
418             this.progress = progress;
419         }
420         public int getTotal() {
421             return total;
422         }
423         protected void setTotal(int total) {
424             this.total = total;
425         }
426     }
427
428     private class TransactionParserException extends IllegalStateException {
429         TransactionParserException(String message) {
430             super(message);
431         }
432     }
433 }