]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
refresh transaction list upon database update from the backend
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveTransactionsTask.java
1 /*
2  * Copyright © 2018 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.util.Log;
25
26 import net.ktnx.mobileledger.R;
27 import net.ktnx.mobileledger.TransactionListActivity;
28 import net.ktnx.mobileledger.model.LedgerTransaction;
29 import net.ktnx.mobileledger.model.LedgerTransactionItem;
30 import net.ktnx.mobileledger.utils.MLDB;
31 import net.ktnx.mobileledger.utils.NetworkUtil;
32
33 import java.io.BufferedReader;
34 import java.io.FileNotFoundException;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.lang.ref.WeakReference;
39 import java.net.HttpURLConnection;
40 import java.net.MalformedURLException;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
43
44
45 public class RetrieveTransactionsTask extends
46         AsyncTask<RetrieveTransactionsTask.Params, RetrieveTransactionsTask.Progress, Void> {
47     private static final Pattern transactionStartPattern = Pattern.compile("<tr class=\"title\" " +
48                                                                            "id=\"transaction-(\\d+)\"><td class=\"date\"[^\\\"]*>([\\d.-]+)</td>");
49     private static final Pattern transactionDescriptionPattern =
50             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
51     private static final Pattern transactionDetailsPattern =
52             Pattern.compile("^\\s+" + "(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)");
53     private static final Pattern endPattern = Pattern.compile("\\bid=\"addmodal\"");
54     protected WeakReference<TransactionListActivity> contextRef;
55     protected int error;
56     private boolean success;
57     public RetrieveTransactionsTask(WeakReference<TransactionListActivity> contextRef) {
58         this.contextRef = contextRef;
59     }
60     private static final void L(String msg) {
61         Log.d("transaction-parser", msg);
62     }
63     @Override
64     protected void onProgressUpdate(Progress... values) {
65         super.onProgressUpdate(values);
66         TransactionListActivity context = getContext();
67         if (context == null) return;
68         context.onRetrieveProgress(values[0]);
69     }
70     @Override
71     protected void onPreExecute() {
72         super.onPreExecute();
73         TransactionListActivity context = getContext();
74         if (context == null) return;
75         context.onRetrieveStart();
76     }
77     @Override
78     protected void onPostExecute(Void aVoid) {
79         super.onPostExecute(aVoid);
80         TransactionListActivity context = getContext();
81         if (context == null) return;
82         context.onRetrieveDone(success);
83     }
84     @SuppressLint("DefaultLocale")
85     @Override
86     protected Void doInBackground(Params... params) {
87         Progress progress = new Progress();
88         success = false;
89         try {
90             HttpURLConnection http =
91                     NetworkUtil.prepare_connection(params[0].getBackendPref(), "journal");
92             http.setAllowUserInteraction(false);
93             publishProgress(progress);
94             TransactionListActivity ctx = contextRef.get();
95             if (ctx == null) return null;
96             try (SQLiteDatabase db = MLDB.getWritableDatabase(ctx)) {
97                 try (InputStream resp = http.getInputStream()) {
98                     if (http.getResponseCode() != 200) throw new IOException(
99                             String.format("HTTP error %d", http.getResponseCode()));
100                     db.beginTransaction();
101                     try {
102                         db.execSQL("DELETE FROM transactions;");
103                         db.execSQL("DELETE FROM transaction_accounts");
104
105                         int state = ParserState.EXPECTING_JOURNAL;
106                         String line;
107                         BufferedReader buf =
108                                 new BufferedReader(new InputStreamReader(resp, "UTF-8"));
109
110                         int transactionCount = 0;
111                         int transactionId = 0;
112                         LedgerTransaction transaction = null;
113                         LINES:
114                         while ((line = buf.readLine()) != null) {
115                             if (isCancelled()) break;
116                             Matcher m;
117                             //L(String.format("State is %d", state));
118                             switch (state) {
119                                 case ParserState.EXPECTING_JOURNAL:
120                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
121                                     if (line.equals("<h2>General Journal</h2>")) {
122                                         state = ParserState.EXPECTING_TRANSACTION;
123                                         L("→ expecting transaction");
124                                     }
125                                     break;
126                                 case ParserState.EXPECTING_TRANSACTION:
127                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
128                                     m = transactionStartPattern.matcher(line);
129                                     if (m.find()) {
130                                         transactionId = Integer.valueOf(m.group(1));
131                                         state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
132                                         L(String.format(
133                                                 "found transaction %d → expecting " + "description",
134                                                 transactionId));
135                                         progress.setProgress(++transactionCount);
136                                         if (progress.getTotal() == Progress.INDETERMINATE)
137                                             progress.setTotal(transactionId);
138                                         publishProgress(progress);
139                                     }
140                                     m = endPattern.matcher(line);
141                                     if (m.find()) {
142                                         L("--- transaction list complete ---");
143                                         success = true;
144                                         break LINES;
145                                     }
146                                     break;
147                                 case ParserState.EXPECTING_TRANSACTION_DESCRIPTION:
148                                     if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
149                                     m = transactionDescriptionPattern.matcher(line);
150                                     if (m.find()) {
151                                         if (transactionId == 0)
152                                             throw new TransactionParserException(
153                                                     "Transaction Id is 0 while expecting " +
154                                                     "description");
155
156                                         transaction =
157                                                 new LedgerTransaction(transactionId, m.group(1),
158                                                         m.group(2));
159                                         state = ParserState.EXPECTING_TRANSACTION_DETAILS;
160                                         L(String.format("transaction %d created for %s (%s) →" +
161                                                         " expecting details", transactionId,
162                                                 m.group(1), m.group(2)));
163                                     }
164                                     break;
165                                 case ParserState.EXPECTING_TRANSACTION_DETAILS:
166                                     if (line.isEmpty()) {
167                                         // transaction data collected
168                                         transaction.insertInto(db);
169
170                                         state = ParserState.EXPECTING_TRANSACTION;
171                                         L(String.format(
172                                                 "transaction %s saved → expecting " + "transaction",
173                                                 transaction.getId()));
174
175 // sounds like a good idea, but transaction-1 may not be the first one chronologically
176 // for example, when you add the initial seeding transaction after entering some others
177 //                                            if (transactionId == 1) {
178 //                                                L("This was the initial transaction. Terminating " +
179 //                                                  "parser");
180 //                                                break LINES;
181 //                                            }
182                                     }
183                                     else {
184                                         m = transactionDetailsPattern.matcher(line);
185                                         if (m.find()) {
186                                             String acc_name = m.group(1);
187                                             String amount = m.group(2);
188                                             amount = amount.replace(',', '.');
189                                             transaction.add_item(new LedgerTransactionItem(acc_name,
190                                                     Float.valueOf(amount)));
191                                             L(String.format("%s = %s", acc_name, amount));
192                                         }
193                                         else throw new IllegalStateException(
194                                                 String.format("Can't parse transaction details"));
195                                     }
196                                     break;
197                                 default:
198                                     throw new RuntimeException(
199                                             String.format("Unknown " + "parser state %d", state));
200                             }
201                         }
202                         if (!isCancelled()) db.setTransactionSuccessful();
203                     }
204                     finally {
205                         db.endTransaction();
206                     }
207                 }
208             }
209
210             if (success && !isCancelled()) ctx.model.reloadTransactions(ctx);
211         }
212         catch (MalformedURLException e) {
213             error = R.string.err_bad_backend_url;
214             e.printStackTrace();
215         }
216         catch (FileNotFoundException e) {
217             error = R.string.err_bad_auth;
218             e.printStackTrace();
219         }
220         catch (IOException e) {
221             error = R.string.err_net_io_error;
222             e.printStackTrace();
223         }
224         return null;
225     }
226     TransactionListActivity getContext() {
227         return contextRef.get();
228     }
229
230     public static class Params {
231         static final int DEFAULT_LIMIT = 100;
232         private SharedPreferences backendPref;
233         private String accountsRoot;
234         private int limit;
235
236         public Params(SharedPreferences backendPref) {
237             this.backendPref = backendPref;
238             this.accountsRoot = null;
239             this.limit = DEFAULT_LIMIT;
240         }
241         Params(SharedPreferences backendPref, String accountsRoot) {
242             this(backendPref, accountsRoot, DEFAULT_LIMIT);
243         }
244         Params(SharedPreferences backendPref, String accountsRoot, int limit) {
245             this.backendPref = backendPref;
246             this.accountsRoot = accountsRoot;
247             this.limit = limit;
248         }
249         String getAccountsRoot() {
250             return accountsRoot;
251         }
252         SharedPreferences getBackendPref() {
253             return backendPref;
254         }
255         int getLimit() {
256             return limit;
257         }
258     }
259
260     public class Progress {
261         public static final int INDETERMINATE = -1;
262         private int progress;
263         private int total;
264         Progress() {
265             this(INDETERMINATE, INDETERMINATE);
266         }
267         Progress(int progress, int total) {
268             this.progress = progress;
269             this.total = total;
270         }
271         public int getProgress() {
272             return progress;
273         }
274         protected void setProgress(int progress) {
275             this.progress = progress;
276         }
277         public int getTotal() {
278             return total;
279         }
280         protected void setTotal(int total) {
281             this.total = total;
282         }
283     }
284
285     private class TransactionParserException extends IllegalStateException {
286         TransactionParserException(String message) {
287             super(message);
288         }
289     }
290
291     private class ParserState {
292         static final int EXPECTING_JOURNAL = 0;
293         static final int EXPECTING_TRANSACTION = 1;
294         static final int EXPECTING_TRANSACTION_DESCRIPTION = 2;
295         static final int EXPECTING_TRANSACTION_DETAILS = 3;
296     }
297 }