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