unused variable
[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.R;
27 import net.ktnx.mobileledger.model.Data;
28 import net.ktnx.mobileledger.model.LedgerAccount;
29 import net.ktnx.mobileledger.model.LedgerTransaction;
30 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
31 import net.ktnx.mobileledger.model.MobileLedgerProfile;
32 import net.ktnx.mobileledger.ui.activity.MainActivity;
33 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
34 import net.ktnx.mobileledger.utils.MLDB;
35 import net.ktnx.mobileledger.utils.NetworkUtil;
36
37 import java.io.BufferedReader;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.io.InputStreamReader;
42 import java.lang.ref.WeakReference;
43 import java.net.HttpURLConnection;
44 import java.net.MalformedURLException;
45 import java.net.URLDecoder;
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, Void> {
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 boolean success;
69     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
70     private Pattern reAccountValue = Pattern.compile(
71             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
72     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef) {
73         this.contextRef = contextRef;
74     }
75     private static void L(String msg) {
76         Log.d("transaction-parser", msg);
77     }
78     @Override
79     protected void onProgressUpdate(Progress... values) {
80         super.onProgressUpdate(values);
81         MainActivity context = getContext();
82         if (context == null) return;
83         context.onRetrieveProgress(values[0]);
84     }
85     @Override
86     protected void onPreExecute() {
87         super.onPreExecute();
88         MainActivity context = getContext();
89         if (context == null) return;
90         context.onRetrieveStart();
91     }
92     @Override
93     protected void onPostExecute(Void aVoid) {
94         super.onPostExecute(aVoid);
95         MainActivity context = getContext();
96         if (context == null) return;
97         context.onRetrieveDone(success);
98     }
99     @Override
100     protected void onCancelled() {
101         super.onCancelled();
102         MainActivity context = getContext();
103         if (context == null) return;
104         context.onRetrieveDone(false);
105     }
106     @SuppressLint("DefaultLocale")
107     @Override
108     protected Void doInBackground(Void... params) {
109         MobileLedgerProfile profile = Data.profile.get();
110         Progress progress = new Progress();
111         int maxTransactionId = Progress.INDETERMINATE;
112         success = false;
113         ArrayList<LedgerAccount> accountList = new ArrayList<>();
114         HashMap<String, Void> accountNames = new HashMap<>();
115         LedgerAccount lastAccount = null;
116         boolean onlyStarred = Data.optShowOnlyStarred.get();
117         Data.backgroundTaskCount.incrementAndGet();
118         try {
119             HttpURLConnection http = NetworkUtil.prepareConnection("journal");
120             http.setAllowUserInteraction(false);
121             publishProgress(progress);
122             MainActivity ctx = getContext();
123             if (ctx == null) return null;
124             try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
125                 try (InputStream resp = http.getInputStream()) {
126                     if (http.getResponseCode() != 200) throw new IOException(
127                             String.format("HTTP error %d", http.getResponseCode()));
128                     db.beginTransaction();
129                     try {
130                         db.execSQL("UPDATE transactions set keep=0");
131                         db.execSQL("update account_values set keep=0;");
132                         db.execSQL("update accounts set keep=0;");
133
134                         ParserState state = ParserState.EXPECTING_ACCOUNT;
135                         String line;
136                         BufferedReader buf =
137                                 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
138
139                         int processedTransactionCount = 0;
140                         int transactionId = 0;
141                         int matchedTransactionsCount = 0;
142                         LedgerTransaction transaction = null;
143                         LINES:
144                         while ((line = buf.readLine()) != null) {
145                             throwIfCancelled();
146                             Matcher m;
147                             m = reComment.matcher(line);
148                             if (m.find()) {
149                                 // TODO: comments are ignored for now
150                                 Log.v("transaction-parser", "Ignoring comment");
151                                 continue;
152                             }
153                             //L(String.format("State is %d", updating));
154                             switch (state) {
155                                 case EXPECTING_ACCOUNT:
156                                     if (line.equals("<h2>General Journal</h2>")) {
157                                         state = ParserState.EXPECTING_TRANSACTION;
158                                         L("→ expecting transaction");
159                                         Data.accounts.set(accountList);
160                                         continue;
161                                     }
162                                     m = reAccountName.matcher(line);
163                                     if (m.find()) {
164                                         String acct_encoded = m.group(1);
165                                         String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
166                                         acct_name = acct_name.replace("\"", "");
167                                         L(String.format("found account: %s", acct_name));
168
169                                         lastAccount = profile.loadAccount(acct_name);
170                                         if (lastAccount == null) {
171                                             lastAccount = new LedgerAccount(acct_name);
172                                             profile.storeAccount(lastAccount);
173                                         }
174
175                                         // make sure the parent account(s) are present,
176                                         // synthesising them if necessary
177                                         String parentName = lastAccount.getParentName();
178                                         if (parentName != null) {
179                                             Stack<String> toAppend = new Stack<>();
180                                             while (parentName != null) {
181                                                 if (accountNames.containsKey(parentName)) break;
182                                                 toAppend.push(parentName);
183                                                 parentName = new LedgerAccount(parentName)
184                                                         .getParentName();
185                                             }
186                                             while (!toAppend.isEmpty()) {
187                                                 String aName = toAppend.pop();
188                                                 LedgerAccount acc = new LedgerAccount(aName);
189                                                 acc.setHidden(lastAccount.isHidden());
190                                                 if (!onlyStarred || !acc.isHidden())
191                                                     accountList.add(acc);
192                                                 L(String.format("gap-filling with %s", aName));
193                                                 accountNames.put(aName, null);
194                                                 profile.storeAccount(acc);
195                                             }
196                                         }
197
198                                         if (!onlyStarred || !lastAccount.isHidden())
199                                             accountList.add(lastAccount);
200                                         accountNames.put(acct_name, null);
201
202                                         state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
203                                         L("→ expecting account amount");
204                                     }
205                                     break;
206
207                                 case EXPECTING_ACCOUNT_AMOUNT:
208                                     m = reAccountValue.matcher(line);
209                                     boolean match_found = false;
210                                     while (m.find()) {
211                                         throwIfCancelled();
212
213                                         match_found = true;
214                                         String value = m.group(1);
215                                         String currency = m.group(2);
216                                         if (currency == null) currency = "";
217                                         value = value.replace(',', '.');
218                                         L("curr=" + currency + ", value=" + value);
219                                         profile.storeAccountValue(lastAccount.getName(), currency,
220                                                 Float.valueOf(value));
221                                         lastAccount.addAmount(Float.parseFloat(value), currency);
222                                     }
223
224                                     if (match_found) {
225                                         state = ParserState.EXPECTING_ACCOUNT;
226                                         L("→ expecting account");
227                                     }
228
229                                     break;
230
231                                 case EXPECTING_TRANSACTION:
232                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
233                                     m = reTransactionStart.matcher(line);
234                                     if (m.find()) {
235                                         transactionId = Integer.valueOf(m.group(1));
236                                         state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
237                                         L(String.format(
238                                                 "found transaction %d → expecting description",
239                                                 transactionId));
240                                         progress.setProgress(++processedTransactionCount);
241                                         if (maxTransactionId < transactionId)
242                                             maxTransactionId = transactionId;
243                                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
244                                             (progress.getTotal() < transactionId))
245                                             progress.setTotal(transactionId);
246                                         publishProgress(progress);
247                                     }
248                                     m = reEnd.matcher(line);
249                                     if (m.find()) {
250                                         L("--- transaction value complete ---");
251                                         success = true;
252                                         break LINES;
253                                     }
254                                     break;
255
256                                 case EXPECTING_TRANSACTION_DESCRIPTION:
257                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
258                                     m = reTransactionDescription.matcher(line);
259                                     if (m.find()) {
260                                         if (transactionId == 0)
261                                             throw new TransactionParserException(
262                                                     "Transaction Id is 0 while expecting " +
263                                                     "description");
264
265                                         transaction =
266                                                 new LedgerTransaction(transactionId, m.group(1),
267                                                         m.group(2));
268                                         state = ParserState.EXPECTING_TRANSACTION_DETAILS;
269                                         L(String.format("transaction %d created for %s (%s) →" +
270                                                         " expecting details", transactionId,
271                                                 m.group(1), m.group(2)));
272                                     }
273                                     break;
274
275                                 case EXPECTING_TRANSACTION_DETAILS:
276                                     if (line.isEmpty()) {
277                                         // transaction data collected
278                                         if (transaction.existsInDb(db)) {
279                                             db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
280                                                        "profile = ? and id=?",
281                                                     new Object[]{profile.getUuid(),
282                                                                  transaction.getId()
283                                                     });
284                                             matchedTransactionsCount++;
285
286                                             if (matchedTransactionsCount ==
287                                                 MATCHING_TRANSACTIONS_LIMIT)
288                                             {
289                                                 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
290                                                            "profile = ? and id < ?",
291                                                         new Object[]{profile.getUuid(),
292                                                                      transaction.getId()
293                                                         });
294                                                 success = true;
295                                                 progress.setTotal(progress.getProgress());
296                                                 publishProgress(progress);
297                                                 break LINES;
298                                             }
299                                         }
300                                         else {
301                                             profile.storeTransaction(transaction);
302                                             matchedTransactionsCount = 0;
303                                             progress.setTotal(maxTransactionId);
304                                         }
305
306                                         state = ParserState.EXPECTING_TRANSACTION;
307                                         L(String.format(
308                                                 "transaction %s saved → expecting transaction",
309                                                 transaction.getId()));
310                                         transaction.finishLoading();
311
312 // sounds like a good idea, but transaction-1 may not be the first one chronologically
313 // for example, when you add the initial seeding transaction after entering some others
314 //                                            if (transactionId == 1) {
315 //                                                L("This was the initial transaction. Terminating " +
316 //                                                  "parser");
317 //                                                break LINES;
318 //                                            }
319                                     }
320                                     else {
321                                         m = reTransactionDetails.matcher(line);
322                                         if (m.find()) {
323                                             String acc_name = m.group(1);
324                                             String amount = m.group(2);
325                                             String currency = m.group(3);
326                                             if (currency == null) currency = "";
327                                             amount = amount.replace(',', '.');
328                                             transaction.addAccount(
329                                                     new LedgerTransactionAccount(acc_name,
330                                                             Float.valueOf(amount), currency));
331                                             L(String.format("%d: %s = %s", transaction.getId(),
332                                                     acc_name, amount));
333                                         }
334                                         else throw new IllegalStateException(String.format(
335                                                 "Can't parse transaction %d " + "details: %s",
336                                                 transactionId, line));
337                                     }
338                                     break;
339                                 default:
340                                     throw new RuntimeException(
341                                             String.format("Unknown parser updating %s",
342                                                     state.name()));
343                             }
344                         }
345
346                         throwIfCancelled();
347
348                         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0",
349                                 new String[]{profile.getUuid()});
350                         db.setTransactionSuccessful();
351
352                         Log.d("db", "Updating transaction value stamp");
353                         Date now = new Date();
354                         profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
355                         Data.lastUpdateDate.set(now);
356                         TransactionListViewModel.scheduleTransactionListReload();
357                     }
358                     finally {
359                         db.endTransaction();
360                     }
361                 }
362             }
363         }
364         catch (MalformedURLException e) {
365             error = R.string.err_bad_backend_url;
366             e.printStackTrace();
367         }
368         catch (FileNotFoundException e) {
369             error = R.string.err_bad_auth;
370             e.printStackTrace();
371         }
372         catch (IOException e) {
373             error = R.string.err_net_io_error;
374             e.printStackTrace();
375         }
376         catch (OperationCanceledException e) {
377             error = R.string.err_cancelled;
378             e.printStackTrace();
379         }
380         finally {
381             Data.backgroundTaskCount.decrementAndGet();
382         }
383         return null;
384     }
385     private MainActivity getContext() {
386         return contextRef.get();
387     }
388     private void throwIfCancelled() {
389         if (isCancelled()) throw new OperationCanceledException(null);
390     }
391
392     private enum ParserState {
393         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
394         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
395     }
396
397     public class Progress {
398         public static final int INDETERMINATE = -1;
399         private int progress;
400         private int total;
401         Progress() {
402             this(INDETERMINATE, INDETERMINATE);
403         }
404         Progress(int progress, int total) {
405             this.progress = progress;
406             this.total = total;
407         }
408         public int getProgress() {
409             return progress;
410         }
411         protected void setProgress(int progress) {
412             this.progress = progress;
413         }
414         public int getTotal() {
415             return total;
416         }
417         protected void setTotal(int total) {
418             this.total = total;
419         }
420     }
421
422     private class TransactionParserException extends IllegalStateException {
423         TransactionParserException(String message) {
424             super(message);
425         }
426     }
427 }