]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
unused variable
[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.MobileLedgerDatabase;
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 (MobileLedgerDatabase dbh = new MobileLedgerDatabase(ctx)) {
98                 try (SQLiteDatabase db = dbh.getWritableDatabase()) {
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("DELETE FROM transactions;");
105                             db.execSQL("DELETE FROM transaction_accounts");
106
107                             int state = ParserState.EXPECTING_JOURNAL;
108                             String line;
109                             BufferedReader buf =
110                                     new BufferedReader(new InputStreamReader(resp, "UTF-8"));
111
112                             int transactionCount = 0;
113                             int transactionId = 0;
114                             LedgerTransaction transaction = null;
115                             LINES:
116                             while ((line = buf.readLine()) != null) {
117                                 Matcher m;
118                                 L(String.format("State is %d", state));
119                                 switch (state) {
120                                     case ParserState.EXPECTING_JOURNAL:
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                                         m = transactionStartPattern.matcher(line);
128                                         if (m.find()) {
129                                             transactionId = Integer.valueOf(m.group(1));
130                                             state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
131                                             L(String.format("found transaction %d → expecting " +
132                                                             "description", transactionId));
133                                             progress.setProgress(++transactionCount);
134                                             if (progress.getTotal() == Progress.INDETERMINATE)
135                                                 progress.setTotal(transactionId);
136                                             publishProgress(progress);
137                                         }
138                                         m = endPattern.matcher(line);
139                                         if (m.find()) {
140                                             L("--- transaction list complete ---");
141                                             success = true;
142                                             break LINES;
143                                         }
144                                         break;
145                                     case ParserState.EXPECTING_TRANSACTION_DESCRIPTION:
146                                         m = transactionDescriptionPattern.matcher(line);
147                                         if (m.find()) {
148                                             if (transactionId == 0)
149                                                 throw new TransactionParserException(
150                                                         "Transaction Id is 0 while expecting " +
151                                                         "description");
152
153                                             transaction =
154                                                     new LedgerTransaction(transactionId, m.group(1),
155                                                             m.group(2));
156                                             state = ParserState.EXPECTING_TRANSACTION_DETAILS;
157                                             L(String.format("transaction %d created for %s (%s) →" +
158                                                             " expecting details", transactionId,
159                                                     m.group(1), m.group(2)));
160                                         }
161                                         break;
162                                     case ParserState.EXPECTING_TRANSACTION_DETAILS:
163                                         if (line.isEmpty()) {
164                                             // transaction data collected
165                                             transaction.insertInto(db);
166
167                                             state = ParserState.EXPECTING_TRANSACTION;
168                                             L(String.format("transaction %s saved → expecting " +
169                                                             "transaction", transaction.getId()));
170                                         }
171                                         else {
172                                             m = transactionDetailsPattern.matcher(line);
173                                             if (m.find()) {
174                                                 String acc_name = m.group(1);
175                                                 String amount = m.group(2);
176                                                 amount = amount.replace(',', '.');
177                                                 transaction.add_item(
178                                                         new LedgerTransactionItem(acc_name,
179                                                                 Float.valueOf(amount)));
180                                                 L(String.format("%s = %s", acc_name, amount));
181                                             }
182                                             else throw new IllegalStateException(String.format(
183                                                     "Can't parse transaction details"));
184                                         }
185                                         break;
186                                     default:
187                                         throw new RuntimeException(
188                                                 String.format("Unknown " + "parser state %d",
189                                                         state));
190                                 }
191                             }
192                             db.setTransactionSuccessful();
193                         }
194                         finally {
195                             db.endTransaction();
196                         }
197                     }
198                 }
199             }
200         }
201         catch (MalformedURLException e) {
202             error = R.string.err_bad_backend_url;
203             e.printStackTrace();
204         }
205         catch (FileNotFoundException e) {
206             error = R.string.err_bad_auth;
207             e.printStackTrace();
208         }
209         catch (IOException e) {
210             error = R.string.err_net_io_error;
211             e.printStackTrace();
212         }
213         return null;
214     }
215     TransactionListActivity getContext() {
216         return contextRef.get();
217     }
218
219     public static class Params {
220         static final int DEFAULT_LIMIT = 100;
221         private SharedPreferences backendPref;
222         private String accountsRoot;
223         private int limit;
224
225         public Params(SharedPreferences backendPref) {
226             this.backendPref = backendPref;
227             this.accountsRoot = null;
228             this.limit = DEFAULT_LIMIT;
229         }
230         Params(SharedPreferences backendPref, String accountsRoot) {
231             this(backendPref, accountsRoot, DEFAULT_LIMIT);
232         }
233         Params(SharedPreferences backendPref, String accountsRoot, int limit) {
234             this.backendPref = backendPref;
235             this.accountsRoot = accountsRoot;
236             this.limit = limit;
237         }
238         String getAccountsRoot() {
239             return accountsRoot;
240         }
241         SharedPreferences getBackendPref() {
242             return backendPref;
243         }
244         int getLimit() {
245             return limit;
246         }
247     }
248
249     public class Progress {
250         public static final int INDETERMINATE = -1;
251         private int progress;
252         private int total;
253         Progress() {
254             this(INDETERMINATE, INDETERMINATE);
255         }
256         Progress(int progress, int total) {
257             this.progress = progress;
258             this.total = total;
259         }
260         public int getProgress() {
261             return progress;
262         }
263         protected void setProgress(int progress) {
264             this.progress = progress;
265         }
266         public int getTotal() {
267             return total;
268         }
269         protected void setTotal(int total) {
270             this.total = total;
271         }
272     }
273
274     private class TransactionParserException extends IllegalStateException {
275         TransactionParserException(String message) {
276             super(message);
277         }
278     }
279
280     private class ParserState {
281         static final int EXPECTING_JOURNAL = 0;
282         static final int EXPECTING_TRANSACTION = 1;
283         static final int EXPECTING_TRANSACTION_DESCRIPTION = 2;
284         static final int EXPECTING_TRANSACTION_DETAILS = 3;
285     }
286 }