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