]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
somewhat complete profile implementation
[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                                         profile.storeAccount(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                                         profile.storeAccountValue(lastAccount.getName(), currency,
185                                                 Float.valueOf(value));
186                                         lastAccount.addAmount(Float.parseFloat(value), currency);
187                                     }
188
189                                     if (match_found) {
190                                         state = ParserState.EXPECTING_ACCOUNT;
191                                         L("→ expecting account");
192                                     }
193
194                                     break;
195
196                                 case EXPECTING_TRANSACTION:
197                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
198                                     m = transactionStartPattern.matcher(line);
199                                     if (m.find()) {
200                                         transactionId = Integer.valueOf(m.group(1));
201                                         state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
202                                         L(String.format(
203                                                 "found transaction %d → expecting description",
204                                                 transactionId));
205                                         progress.setProgress(++processedTransactionCount);
206                                         if (maxTransactionId < transactionId)
207                                             maxTransactionId = transactionId;
208                                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
209                                             (progress.getTotal() < transactionId))
210                                             progress.setTotal(transactionId);
211                                         publishProgress(progress);
212                                     }
213                                     m = endPattern.matcher(line);
214                                     if (m.find()) {
215                                         L("--- transaction value complete ---");
216                                         success = true;
217                                         break LINES;
218                                     }
219                                     break;
220
221                                 case EXPECTING_TRANSACTION_DESCRIPTION:
222                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
223                                     m = transactionDescriptionPattern.matcher(line);
224                                     if (m.find()) {
225                                         if (transactionId == 0)
226                                             throw new TransactionParserException(
227                                                     "Transaction Id is 0 while expecting " +
228                                                     "description");
229
230                                         transaction =
231                                                 new LedgerTransaction(transactionId, m.group(1),
232                                                         m.group(2));
233                                         state = ParserState.EXPECTING_TRANSACTION_DETAILS;
234                                         L(String.format("transaction %d created for %s (%s) →" +
235                                                         " expecting details", transactionId,
236                                                 m.group(1), m.group(2)));
237                                     }
238                                     break;
239
240                                 case EXPECTING_TRANSACTION_DETAILS:
241                                     if (line.isEmpty()) {
242                                         // transaction data collected
243                                         if (transaction.existsInDb(db)) {
244                                             db.execSQL("UPDATE transactions SET keep = 1 WHERE " +
245                                                        "profile = ? and id=?",
246                                                     new Object[]{profile.getUuid(),
247                                                                  transaction.getId()
248                                                     });
249                                             matchedTransactionsCount++;
250
251                                             if (matchedTransactionsCount ==
252                                                 MATCHING_TRANSACTIONS_LIMIT)
253                                             {
254                                                 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
255                                                            "profile = ? and id < ?",
256                                                         new Object[]{profile.getUuid(),
257                                                                      transaction.getId()
258                                                         });
259                                                 success = true;
260                                                 progress.setTotal(progress.getProgress());
261                                                 publishProgress(progress);
262                                                 break LINES;
263                                             }
264                                         }
265                                         else {
266                                             profile.storeTransaction(transaction);
267                                             matchedTransactionsCount = 0;
268                                             progress.setTotal(maxTransactionId);
269                                         }
270
271                                         state = ParserState.EXPECTING_TRANSACTION;
272                                         L(String.format(
273                                                 "transaction %s saved → expecting transaction",
274                                                 transaction.getId()));
275                                         transaction.finishLoading();
276                                         transactionList.add(transaction);
277
278 // sounds like a good idea, but transaction-1 may not be the first one chronologically
279 // for example, when you add the initial seeding transaction after entering some others
280 //                                            if (transactionId == 1) {
281 //                                                L("This was the initial transaction. Terminating " +
282 //                                                  "parser");
283 //                                                break LINES;
284 //                                            }
285                                     }
286                                     else {
287                                         m = transactionDetailsPattern.matcher(line);
288                                         if (m.find()) {
289                                             String acc_name = m.group(1);
290                                             String amount = m.group(2);
291                                             String currency = m.group(3);
292                                             if (currency == null) currency = "";
293                                             amount = amount.replace(',', '.');
294                                             transaction.addAccount(
295                                                     new LedgerTransactionAccount(acc_name,
296                                                             Float.valueOf(amount), currency));
297                                             L(String.format("%d: %s = %s", transaction.getId(),
298                                                     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 profile=? AND keep = 0",
315                                 new String[]{profile.getUuid()});
316                         db.setTransactionSuccessful();
317
318                         Log.d("db", "Updating transaction value stamp");
319                         Date now = new Date();
320                         profile.set_option_value(MLDB.OPT_LAST_SCRAPE, now.getTime());
321                         Data.lastUpdateDate.set(now);
322                         Data.transactions.set(transactionList);
323                     }
324                     finally {
325                         db.endTransaction();
326                     }
327                 }
328             }
329         }
330         catch (MalformedURLException e) {
331             error = R.string.err_bad_backend_url;
332             e.printStackTrace();
333         }
334         catch (FileNotFoundException e) {
335             error = R.string.err_bad_auth;
336             e.printStackTrace();
337         }
338         catch (IOException e) {
339             error = R.string.err_net_io_error;
340             e.printStackTrace();
341         }
342         catch (OperationCanceledException e) {
343             error = R.string.err_cancelled;
344             e.printStackTrace();
345         }
346         finally {
347             Data.backgroundTaskCount.decrementAndGet();
348         }
349         return null;
350     }
351     private MainActivity getContext() {
352         return contextRef.get();
353     }
354     private void throwIfCancelled() {
355         if (isCancelled()) throw new OperationCanceledException(null);
356     }
357
358     private enum ParserState {
359         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
360         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
361     }
362
363     public class Progress {
364         public static final int INDETERMINATE = -1;
365         private int progress;
366         private int total;
367         Progress() {
368             this(INDETERMINATE, INDETERMINATE);
369         }
370         Progress(int progress, int total) {
371             this.progress = progress;
372             this.total = total;
373         }
374         public int getProgress() {
375             return progress;
376         }
377         protected void setProgress(int progress) {
378             this.progress = progress;
379         }
380         public int getTotal() {
381             return total;
382         }
383         protected void setTotal(int total) {
384             this.total = total;
385         }
386     }
387
388     private class TransactionParserException extends IllegalStateException {
389         TransactionParserException(String message) {
390             super(message);
391         }
392     }
393 }