]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
parse and show ledger name
[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.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 extends
52         AsyncTask<RetrieveTransactionsTask.Params, 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     // %3A is '='
64     private Pattern ledger_title_re = Pattern.compile("<h1>([^<]+)</h1>");
65     Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
66     Pattern account_value_re = Pattern.compile(
67             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
68     Pattern tr_end_re = Pattern.compile("</tr>");
69     Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
70     Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
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(Params... params) {
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 =
118                     NetworkUtil.prepare_connection(params[0].getBackendPref(), "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                             //L(String.format("State is %d", updating));
149                             switch (state) {
150                                 case EXPECTING_ACCOUNT:
151                                     if (line.equals("<h2>General Journal</h2>")) {
152                                         state = ParserState.EXPECTING_TRANSACTION;
153                                         L("→ expecting transaction");
154                                         Data.accounts.set(accountList);
155                                         continue;
156                                     }
157                                     m = account_name_re.matcher(line);
158                                     if (m.find()) {
159                                         String acct_encoded = m.group(1);
160                                         String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
161                                         acct_name = acct_name.replace("\"", "");
162                                         L(String.format("found account: %s", acct_name));
163
164                                         addAccount(db, acct_name);
165                                         lastAccount = new LedgerAccount(acct_name);
166                                         accountList.add(lastAccount);
167
168                                         state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
169                                         L("→ expecting account amount");
170                                     }
171                                     else if (ledgerTitle == null) {
172                                         m = ledger_title_re.matcher(line);
173                                         if (m.find()) {
174                                             ledgerTitle = m.group(1);
175                                             Data.ledgerTitle.set(ledgerTitle);
176                                         }
177                                     }
178                                     break;
179
180                                 case EXPECTING_ACCOUNT_AMOUNT:
181                                     m = account_value_re.matcher(line);
182                                     boolean match_found = false;
183                                     while (m.find()) {
184                                         throwIfCancelled();
185
186                                         match_found = true;
187                                         String value = m.group(1);
188                                         String currency = m.group(2);
189                                         if (currency == null) currency = "";
190                                         value = value.replace(',', '.');
191                                         L("curr=" + currency + ", value=" + value);
192                                         db.execSQL(
193                                                 "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
194                                                 new Object[]{lastAccount.getName(), currency,
195                                                              Float.valueOf(value)
196                                                 });
197                                         lastAccount.addAmount(Float.parseFloat(value), currency);
198                                     }
199
200                                     if (match_found) {
201                                         state = ParserState.EXPECTING_ACCOUNT;
202                                         L("→ expecting account");
203                                     }
204
205                                     break;
206
207                                 case EXPECTING_TRANSACTION:
208                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
209                                     m = transactionStartPattern.matcher(line);
210                                     if (m.find()) {
211                                         transactionId = Integer.valueOf(m.group(1));
212                                         state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
213                                         L(String.format(
214                                                 "found transaction %d → expecting description",
215                                                 transactionId));
216                                         progress.setProgress(++processedTransactionCount);
217                                         if (maxTransactionId < transactionId)
218                                             maxTransactionId = transactionId;
219                                         if ((progress.getTotal() == Progress.INDETERMINATE) ||
220                                             (progress.getTotal() < transactionId))
221                                             progress.setTotal(transactionId);
222                                         publishProgress(progress);
223                                     }
224                                     m = endPattern.matcher(line);
225                                     if (m.find()) {
226                                         L("--- transaction value complete ---");
227                                         success = true;
228                                         break LINES;
229                                     }
230                                     break;
231
232                                 case EXPECTING_TRANSACTION_DESCRIPTION:
233                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
234                                     m = transactionDescriptionPattern.matcher(line);
235                                     if (m.find()) {
236                                         if (transactionId == 0)
237                                             throw new TransactionParserException(
238                                                     "Transaction Id is 0 while expecting " +
239                                                     "description");
240
241                                         transaction =
242                                                 new LedgerTransaction(transactionId, m.group(1),
243                                                         m.group(2));
244                                         state = ParserState.EXPECTING_TRANSACTION_DETAILS;
245                                         L(String.format("transaction %d created for %s (%s) →" +
246                                                         " expecting details", transactionId,
247                                                 m.group(1), m.group(2)));
248                                     }
249                                     break;
250
251                                 case EXPECTING_TRANSACTION_DETAILS:
252                                     if (line.isEmpty()) {
253                                         // transaction data collected
254                                         if (transaction.existsInDb(db)) {
255                                             db.execSQL("UPDATE transactions SET keep = 1 WHERE id" +
256                                                        "=?", new Integer[]{transaction.getId()});
257                                             matchedTransactionsCount++;
258
259                                             if (matchedTransactionsCount ==
260                                                 MATCHING_TRANSACTIONS_LIMIT)
261                                             {
262                                                 db.execSQL("UPDATE transactions SET keep=1 WHERE " +
263                                                            "id < ?",
264                                                         new Integer[]{transaction.getId()});
265                                                 success = true;
266                                                 progress.setTotal(progress.getProgress());
267                                                 publishProgress(progress);
268                                                 break LINES;
269                                             }
270                                         }
271                                         else {
272                                             db.execSQL("DELETE from transactions WHERE id=?",
273                                                     new Integer[]{transaction.getId()});
274                                             db.execSQL("DELETE from transaction_accounts WHERE " +
275                                                        "transaction_id=?",
276                                                     new Integer[]{transaction.getId()});
277                                             transaction.insertInto(db);
278                                             matchedTransactionsCount = 0;
279                                             progress.setTotal(maxTransactionId);
280                                         }
281
282                                         state = ParserState.EXPECTING_TRANSACTION;
283                                         L(String.format(
284                                                 "transaction %s saved → expecting transaction",
285                                                 transaction.getId()));
286                                         transactionList.add(transaction);
287
288 // sounds like a good idea, but transaction-1 may not be the first one chronologically
289 // for example, when you add the initial seeding transaction after entering some others
290 //                                            if (transactionId == 1) {
291 //                                                L("This was the initial transaction. Terminating " +
292 //                                                  "parser");
293 //                                                break LINES;
294 //                                            }
295                                     }
296                                     else {
297                                         m = transactionDetailsPattern.matcher(line);
298                                         if (m.find()) {
299                                             String acc_name = m.group(1);
300                                             String amount = m.group(2);
301                                             String currency = m.group(3);
302                                             amount = amount.replace(',', '.');
303                                             transaction.addAccount(
304                                                     new LedgerTransactionAccount(acc_name,
305                                                             Float.valueOf(amount), currency));
306                                             L(String.format("%s = %s", acc_name, amount));
307                                         }
308                                         else throw new IllegalStateException(
309                                                 String.format("Can't parse transaction %d details",
310                                                         transactionId));
311                                     }
312                                     break;
313                                 default:
314                                     throw new RuntimeException(
315                                             String.format("Unknown parser updating %s",
316                                                     state.name()));
317                             }
318                         }
319
320                         throwIfCancelled();
321
322                         db.execSQL("DELETE FROM transactions WHERE keep = 0");
323                         db.setTransactionSuccessful();
324
325                         Log.d("db", "Updating transaction value stamp");
326                         Date now = new Date();
327                         MLDB.set_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, 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 addAccount(SQLiteDatabase db, String name) {
362         do {
363             LedgerAccount acc = new LedgerAccount(name);
364             db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
365                     new Object[]{acc.getLevel(), name});
366             db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
367                        "?,? " + "where (select changes() = 0)",
368                     new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
369             name = acc.getParentName();
370         } while (name != null);
371     }
372     private void throwIfCancelled() {
373         if (isCancelled()) throw new OperationCanceledException(null);
374     }
375
376     private enum ParserState {
377         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
378         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
379     }
380
381     public static class Params {
382         private SharedPreferences backendPref;
383
384         public Params(SharedPreferences backendPref) {
385             this.backendPref = backendPref;
386         }
387         SharedPreferences getBackendPref() {
388             return backendPref;
389         }
390     }
391
392     public class Progress {
393         public static final int INDETERMINATE = -1;
394         private int progress;
395         private int total;
396         Progress() {
397             this(INDETERMINATE, INDETERMINATE);
398         }
399         Progress(int progress, int total) {
400             this.progress = progress;
401             this.total = total;
402         }
403         public int getProgress() {
404             return progress;
405         }
406         protected void setProgress(int progress) {
407             this.progress = progress;
408         }
409         public int getTotal() {
410             return total;
411         }
412         protected void setTotal(int total) {
413             this.total = total;
414         }
415     }
416
417     private class TransactionParserException extends IllegalStateException {
418         TransactionParserException(String message) {
419             super(message);
420         }
421     }
422 }