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