]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/RetrieveAccountsTask.java
add license boilerplates for authored content
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / RetrieveAccountsTask.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;
19
20 import android.content.SharedPreferences;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
23
24 import java.io.BufferedReader;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.lang.ref.WeakReference;
30 import java.net.HttpURLConnection;
31 import java.net.MalformedURLException;
32 import java.net.URLDecoder;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36 class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Void> {
37     int error;
38
39     private SharedPreferences pref;
40     WeakReference<AccountSummary> mContext;
41
42     RetrieveAccountsTask(WeakReference<AccountSummary> context) {
43         mContext = context;
44         error = 0;
45     }
46
47     void setPref(SharedPreferences pref) {
48         this.pref = pref;
49     }
50
51     protected Void doInBackground(Void... params) {
52         try {
53             HttpURLConnection http = NetworkUtil.prepare_connection( pref, "add");
54             http.setAllowUserInteraction(false);
55             http.setRequestProperty("Accept-Charset", "UTF-8");
56             publishProgress(0);
57             try(MobileLedgerDatabase dbh = new MobileLedgerDatabase(mContext.get())) {
58                 try(SQLiteDatabase db = dbh.getWritableDatabase()) {
59                     try (InputStream resp = http.getInputStream()) {
60                         Log.d("update_accounts", String.valueOf(http.getResponseCode()));
61                         if (http.getResponseCode() != 200) {
62                             throw new IOException(
63                                     String.format("HTTP error: %d %s", http.getResponseCode(), http.getResponseMessage()));
64                         }
65                         else {
66                             if (db.inTransaction()) throw new AssertionError();
67
68                             db.beginTransaction();
69
70                             try {
71                                 db.execSQL("update account_values set keep=0;");
72                                 db.execSQL("update accounts set keep=0;");
73
74                                 String line;
75                                 String last_account_name = null;
76                                 BufferedReader buf =
77                                         new BufferedReader(new InputStreamReader(resp, "UTF-8"));
78                                 // %3A is '='
79                                 Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
80                                 Pattern value_re = Pattern.compile(
81                                         "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
82                                 Pattern tr_re = Pattern.compile("</tr>");
83                                 Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
84                                 Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
85                                 int count = 0;
86                                 while ((line = buf.readLine()) != null) {
87                                     Matcher m = account_name_re.matcher(line);
88                                     if (m.find()) {
89                                         String acct_encoded = m.group(1);
90                                         String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
91                                         acct_name = acct_name.replace("\"", "");
92                                         Log.d("account-parser", acct_name);
93
94                                         addAccount(db, acct_name);
95                                         publishProgress(++count);
96
97                                         last_account_name = acct_name;
98
99                                         continue;
100                                     }
101
102                                     Matcher tr_m = tr_re.matcher(line);
103                                     if (tr_m.find()) {
104                                         Log.d("account-parser", "<tr> - another account expected");
105                                         last_account_name = null;
106                                         continue;
107                                     }
108
109                                     if (last_account_name != null) {
110                                         m = value_re.matcher(line);
111                                         boolean match_found = false;
112                                         while (m.find()) {
113                                             match_found = true;
114                                             String value = m.group(1);
115                                             String currency = m.group(2);
116                                             if (currency == null) currency = "";
117                                             value = value.replace(',', '.');
118                                             Log.d("db", "curr=" + currency + ", value=" + value);
119                                             db.execSQL(
120                                                     "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
121                                                     new Object[]{last_account_name, currency, Float.valueOf(value)
122                                                     });
123                                         }
124
125                                         if (match_found) continue;
126                                     }
127
128                                     m = descriptions_line_re.matcher(line);
129                                     if (m.find()) {
130                                         db.execSQL("update description_history set keep=0;");
131                                         m = description_items_re.matcher(line);
132                                         while (m.find()) {
133                                             String description = m.group(1);
134                                             if (description.isEmpty()) continue;
135
136                                             Log.d("db", String.format("Stored description: %s",
137                                                     description));
138                                             db.execSQL("insert or replace into description_history"
139                                                             + "(description, description_upper, keep) " + "values(?, ?, 1);",
140                                                     new Object[]{description, description.toUpperCase()
141                                                     });
142                                         }
143                                     }
144                                 }
145
146                                 db.execSQL("delete from account_values where keep=0;");
147                                 db.execSQL("delete from accounts where keep=0;");
148 //                        db.execSQL("delete from description_history where keep=0;");
149                                 db.setTransactionSuccessful();
150                             }
151                             finally {
152                                 db.endTransaction();
153                             }
154
155                         }
156                     }
157                 }
158             }
159         } catch (MalformedURLException e) {
160             error = R.string.err_bad_backend_url;
161             e.printStackTrace();
162         }
163         catch (FileNotFoundException e) {
164             error = R.string.err_bad_auth;
165             e.printStackTrace();
166         }
167         catch (IOException e) {
168             error = R.string.err_net_io_error;
169             e.printStackTrace();
170         }
171         catch (Exception e) {
172             error = R.string.err_net_error;
173             e.printStackTrace();
174         }
175
176         return null;
177     }
178
179     private void addAccount(SQLiteDatabase db, String name) {
180         do {
181             LedgerAccount acc = new LedgerAccount(name);
182             db.execSQL(
183                     "insert or replace into accounts(name, name_upper, level, parent_name, keep) "
184                             + "values(?, ?, ?, ?, 1)",
185                     new Object[]{name, name.toUpperCase(), acc.getLevel(), acc.getParentName()});
186             name = acc.getParentName();
187         } while (name != null);
188     }
189     @Override
190     protected void onPostExecute(Void result) {
191         AccountSummary ctx = mContext.get();
192         if (ctx == null) return;
193         ctx.onAccountRefreshDone(this.error);
194     }
195
196 }