]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
store table colors in a global glass
[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.LedgerTransactionAccount;
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.addAccount(
219                                                     new LedgerTransactionAccount(acc_name,
220                                                             Float.valueOf(amount)));
221                                             L(String.format("%s = %s", acc_name, amount));
222                                         }
223                                         else throw new IllegalStateException(
224                                                 String.format("Can't parse transaction %d details",
225                                                         transactionId));
226                                     }
227                                     break;
228                                 default:
229                                     throw new RuntimeException(
230                                             String.format("Unknown parser state %d", state));
231                             }
232                         }
233                         if (!isCancelled()) {
234                             db.execSQL("DELETE FROM transactions WHERE keep = 0");
235                             db.setTransactionSuccessful();
236                         }
237                     }
238                     finally {
239                         db.endTransaction();
240                     }
241                 }
242             }
243
244             if (success && !isCancelled()) {
245                 Log.d("db", "Updating transaction list stamp");
246                 MLDB.set_option_value(ctx, MLDB.OPT_TRANSACTION_LIST_STAMP, new Date().getTime());
247                 ctx.model.reloadTransactions(ctx);
248             }
249         }
250         catch (MalformedURLException e) {
251             error = R.string.err_bad_backend_url;
252             e.printStackTrace();
253         }
254         catch (FileNotFoundException e) {
255             error = R.string.err_bad_auth;
256             e.printStackTrace();
257         }
258         catch (IOException e) {
259             error = R.string.err_net_io_error;
260             e.printStackTrace();
261         }
262         return null;
263     }
264     TransactionListActivity getContext() {
265         return contextRef.get();
266     }
267
268     public static class Params {
269         private SharedPreferences backendPref;
270
271         public Params(SharedPreferences backendPref) {
272             this.backendPref = backendPref;
273         }
274         SharedPreferences getBackendPref() {
275             return backendPref;
276         }
277     }
278
279     public class Progress {
280         public static final int INDETERMINATE = -1;
281         private int progress;
282         private int total;
283         Progress() {
284             this(INDETERMINATE, INDETERMINATE);
285         }
286         Progress(int progress, int total) {
287             this.progress = progress;
288             this.total = total;
289         }
290         public int getProgress() {
291             return progress;
292         }
293         protected void setProgress(int progress) {
294             this.progress = progress;
295         }
296         public int getTotal() {
297             return total;
298         }
299         protected void setTotal(int total) {
300             this.total = total;
301         }
302     }
303
304     private class TransactionParserException extends IllegalStateException {
305         TransactionParserException(String message) {
306             super(message);
307         }
308     }
309
310     private class ParserState {
311         static final int EXPECTING_JOURNAL = 0;
312         static final int EXPECTING_TRANSACTION = 1;
313         static final int EXPECTING_TRANSACTION_DESCRIPTION = 2;
314         static final int EXPECTING_TRANSACTION_DETAILS = 3;
315     }
316 }