]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
use profiles for connection parameters
[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     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     Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
64     Pattern account_value_re = Pattern.compile(
65             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
66     Pattern tr_end_re = Pattern.compile("</tr>");
67     Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
68     Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
69     // %3A is '='
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(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         LedgerAccount lastAccount = null;
115         Data.backgroundTaskCount.incrementAndGet();
116         try {
117             HttpURLConnection http = NetworkUtil.prepare_connection("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                         String ledgerTitle = null;
129
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                             //L(String.format("State is %d", updating));
148                             switch (state) {
149                                 case EXPECTING_ACCOUNT:
150                                     if (line.equals("<h2>General Journal</h2>")) {
151                                         state = ParserState.EXPECTING_TRANSACTION;
152                                         L("→ expecting transaction");
153                                         Data.accounts.set(accountList);
154                                         continue;
155                                     }
156                                     m = account_name_re.matcher(line);
157                                     if (m.find()) {
158                                         String acct_encoded = m.group(1);
159                                         String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
160                                         acct_name = acct_name.replace("\"", "");
161                                         L(String.format("found account: %s", acct_name));
162
163                                         addAccount(db, acct_name);
164                                         lastAccount = new LedgerAccount(acct_name);
165                                         accountList.add(lastAccount);
166
167                                         state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
168                                         L("→ expecting account amount");
169                                     }
170                                     break;
171
172                                 case EXPECTING_ACCOUNT_AMOUNT:
173                                     m = account_value_re.matcher(line);
174                                     boolean match_found = false;
175                                     while (m.find()) {
176                                         throwIfCancelled();
177
178                                         match_found = true;
179                                         String value = m.group(1);
180                                         String currency = m.group(2);
181                                         if (currency == null) currency = "";
182                                         value = value.replace(',', '.');
183                                         L("curr=" + currency + ", value=" + value);
184                                         db.execSQL(
185                                                 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
186                                                 new Object[]{lastAccount.getName(), currency,
187                                                              Float.valueOf(value)
188                                                 });
189                                         lastAccount.addAmount(Float.parseFloat(value), currency);
190                                     }
191
192                                     if (match_found) {
193                                         state = ParserState.EXPECTING_ACCOUNT;
194                                         L("→ expecting account");
195                                     }
196
197                                     break;
198
199                                 case EXPECTING_TRANSACTION:
200                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
201                                     m = transactionStartPattern.matcher(line);
202                                     if (m.find()) {
203                                         transactionId = Integer.valueOf(m.group(1));
204                                         state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
205                                         L(String.format(
206                                                 "found transaction %d → expecting description",
207                                                 transactionId));
208                                         progress.setProgress(++processedTransactionCount);
209                                         if (maxTransactionId < transactionId)
210                                             maxTransactionId = transactionId;
211                                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
212                                             (progress.getTotal() < transactionId))
213                                             progress.setTotal(transactionId);
214                                         publishProgress(progress);
215                                     }
216                                     m = endPattern.matcher(line);
217                                     if (m.find()) {
218                                         L("--- transaction value complete ---");
219                                         success = true;
220                                         break LINES;
221                                     }
222                                     break;
223
224                                 case EXPECTING_TRANSACTION_DESCRIPTION:
225                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
226                                     m = transactionDescriptionPattern.matcher(line);
227                                     if (m.find()) {
228                                         if (transactionId == 0)
229                                             throw new TransactionParserException(
230                                                     "Transaction Id is 0 while expecting " +
231                                                     "description");
232
233                                         transaction =
234                                                 new LedgerTransaction(transactionId, m.group(1),
235                                                         m.group(2));
236                                         state = ParserState.EXPECTING_TRANSACTION_DETAILS;
237                                         L(String.format("transaction %d created for %s (%s) →" +
238                                                         " expecting details", transactionId,
239                                                 m.group(1), m.group(2)));
240                                     }
241                                     break;
242
243                                 case EXPECTING_TRANSACTION_DETAILS:
244                                     if (line.isEmpty()) {
245                                         // transaction data collected
246                                         if (transaction.existsInDb(db)) {
247                                             db.execSQL("UPDATE transactions SET keep = 1 WHERE id" +
248                                                        "=?", new Integer[]{transaction.getId()});
249                                             matchedTransactionsCount++;
250
251                                             if (matchedTransactionsCount ==
252                                                 MATCHING_TRANSACTIONS_LIMIT)
253                                             {
254                                                 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
255                                                            "id < ?",
256                                                         new Integer[]{transaction.getId()});
257                                                 success = true;
258                                                 progress.setTotal(progress.getProgress());
259                                                 publishProgress(progress);
260                                                 break LINES;
261                                             }
262                                         }
263                                         else {
264                                             db.execSQL("DELETE from transactions WHERE id=?",
265                                                     new Integer[]{transaction.getId()});
266                                             db.execSQL("DELETE from transaction_accounts WHERE " +
267                                                        "transaction_id=?",
268                                                     new Integer[]{transaction.getId()});
269                                             transaction.insertInto(db);
270                                             matchedTransactionsCount = 0;
271                                             progress.setTotal(maxTransactionId);
272                                         }
273
274                                         state = ParserState.EXPECTING_TRANSACTION;
275                                         L(String.format(
276                                                 "transaction %s saved → expecting transaction",
277                                                 transaction.getId()));
278                                         transactionList.add(transaction);
279
280 // sounds like a good idea, but transaction-1 may not be the first one chronologically
281 // for example, when you add the initial seeding transaction after entering some others
282 //                                            if (transactionId == 1) {
283 //                                                L("This was the initial transaction. Terminating " +
284 //                                                  "parser");
285 //                                                break LINES;
286 //                                            }
287                                     }
288                                     else {
289                                         m = transactionDetailsPattern.matcher(line);
290                                         if (m.find()) {
291                                             String acc_name = m.group(1);
292                                             String amount = m.group(2);
293                                             String currency = m.group(3);
294                                             amount = amount.replace(',', '.');
295                                             transaction.addAccount(
296                                                     new LedgerTransactionAccount(acc_name,
297                                                             Float.valueOf(amount), currency));
298                                             L(String.format("%s = %s", acc_name, amount));
299                                         }
300                                         else throw new IllegalStateException(
301                                                 String.format("Can't parse transaction %d details",
302                                                         transactionId));
303                                     }
304                                     break;
305                                 default:
306                                     throw new RuntimeException(
307                                             String.format("Unknown parser updating %s",
308                                                     state.name()));
309                             }
310                         }
311
312                         throwIfCancelled();
313
314                         db.execSQL("DELETE FROM transactions WHERE keep = 0");
315                         db.setTransactionSuccessful();
316
317                         Log.d("db", "Updating transaction value stamp");
318                         Date now = new Date();
319                         MLDB.set_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, now.getTime());
320                         Data.lastUpdateDate.set(now);
321                         Data.transactions.set(transactionList);
322                     }
323                     finally {
324                         db.endTransaction();
325                     }
326                 }
327             }
328         }
329         catch (MalformedURLException e) {
330             error = R.string.err_bad_backend_url;
331             e.printStackTrace();
332         }
333         catch (FileNotFoundException e) {
334             error = R.string.err_bad_auth;
335             e.printStackTrace();
336         }
337         catch (IOException e) {
338             error = R.string.err_net_io_error;
339             e.printStackTrace();
340         }
341         catch (OperationCanceledException e) {
342             error = R.string.err_cancelled;
343             e.printStackTrace();
344         }
345         finally {
346             Data.backgroundTaskCount.decrementAndGet();
347         }
348         return null;
349     }
350     private MainActivity getContext() {
351         return contextRef.get();
352     }
353     private void addAccount(SQLiteDatabase db, String name) {
354         do {
355             LedgerAccount acc = new LedgerAccount(name);
356             db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
357                     new Object[]{acc.getLevel(), name});
358             db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
359                        "?,? " + "where (select changes() = 0)",
360                     new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
361             name = acc.getParentName();
362         } while (name != null);
363     }
364     private void throwIfCancelled() {
365         if (isCancelled()) throw new OperationCanceledException(null);
366     }
367
368     private enum ParserState {
369         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
370         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
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 }