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