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