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