]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
0354e5ed98e034ae5baee6bf82d17b374a4f14e3
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveTransactionsTask.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe 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  * MoLe 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 MoLe. 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.database.sqlite.SQLiteDatabase;
22 import android.os.AsyncTask;
23 import android.os.OperationCanceledException;
24
25 import androidx.annotation.NonNull;
26
27 import net.ktnx.mobileledger.App;
28 import net.ktnx.mobileledger.err.HTTPException;
29 import net.ktnx.mobileledger.json.AccountListParser;
30 import net.ktnx.mobileledger.json.ParsedBalance;
31 import net.ktnx.mobileledger.json.ParsedLedgerAccount;
32 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
33 import net.ktnx.mobileledger.json.TransactionListParser;
34 import net.ktnx.mobileledger.model.Data;
35 import net.ktnx.mobileledger.model.LedgerAccount;
36 import net.ktnx.mobileledger.model.LedgerTransaction;
37 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
38 import net.ktnx.mobileledger.model.MobileLedgerProfile;
39 import net.ktnx.mobileledger.ui.activity.MainActivity;
40 import net.ktnx.mobileledger.utils.NetworkUtil;
41
42 import java.io.BufferedReader;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.InputStreamReader;
46 import java.lang.ref.WeakReference;
47 import java.net.HttpURLConnection;
48 import java.net.MalformedURLException;
49 import java.net.URLDecoder;
50 import java.nio.charset.StandardCharsets;
51 import java.text.ParseException;
52 import java.util.ArrayList;
53 import java.util.HashMap;
54 import java.util.Locale;
55 import java.util.Stack;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
58
59 import static net.ktnx.mobileledger.utils.Logger.debug;
60
61
62 public class RetrieveTransactionsTask
63         extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
64     private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
65     private static final Pattern reComment = Pattern.compile("^\\s*;");
66     private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
67                                                                       "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
68     private static final Pattern reTransactionDescription =
69             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
70     private static final Pattern reTransactionDetails =
71             Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
72     private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
73     private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
74     private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
75     private WeakReference<MainActivity> contextRef;
76     // %3A is '='
77     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
78     private Pattern reAccountValue = Pattern.compile(
79             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
80     private MobileLedgerProfile profile;
81     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
82                                     @NonNull MobileLedgerProfile profile) {
83         this.contextRef = contextRef;
84         this.profile = profile;
85     }
86     private static void L(String msg) {
87         //debug("transaction-parser", msg);
88     }
89     @Override
90     protected void onProgressUpdate(Progress... values) {
91         super.onProgressUpdate(values);
92         MainActivity context = getContext();
93         if (context == null) return;
94         context.onRetrieveProgress(values[0]);
95     }
96     @Override
97     protected void onPreExecute() {
98         super.onPreExecute();
99         MainActivity context = getContext();
100         if (context == null) return;
101         context.onRetrieveStart();
102     }
103     @Override
104     protected void onPostExecute(String error) {
105         super.onPostExecute(error);
106         MainActivity context = getContext();
107         if (context == null) return;
108         context.onRetrieveDone(error);
109     }
110     @Override
111     protected void onCancelled() {
112         super.onCancelled();
113         MainActivity context = getContext();
114         if (context == null) return;
115         context.onRetrieveDone(null);
116     }
117     private String retrieveTransactionListLegacy()
118             throws IOException, ParseException, HTTPException {
119         Progress progress = new Progress();
120         int maxTransactionId = Progress.INDETERMINATE;
121         ArrayList<LedgerAccount> accountList = new ArrayList<>();
122         HashMap<String, Void> accountNames = new HashMap<>();
123         HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
124         LedgerAccount lastAccount = null, prevAccount = null;
125         boolean onlyStarred = Data.optShowOnlyStarred.get();
126
127         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
128         http.setAllowUserInteraction(false);
129         publishProgress(progress);
130         switch (http.getResponseCode()) {
131             case 200:
132                 break;
133             default:
134                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
135         }
136
137         SQLiteDatabase db = App.getDatabase();
138         try (InputStream resp = http.getInputStream()) {
139             if (http.getResponseCode() != 200)
140                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
141             db.beginTransaction();
142             try {
143                 prepareDbForRetrieval(db, profile);
144
145                 int matchedTransactionsCount = 0;
146
147
148                 ParserState state = ParserState.EXPECTING_ACCOUNT;
149                 String line;
150                 BufferedReader buf =
151                         new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
152
153                 int processedTransactionCount = 0;
154                 int transactionId = 0;
155                 LedgerTransaction transaction = null;
156                 LINES:
157                 while ((line = buf.readLine()) != null) {
158                     throwIfCancelled();
159                     Matcher m;
160                     m = reComment.matcher(line);
161                     if (m.find()) {
162                         // TODO: comments are ignored for now
163 //                            Log.v("transaction-parser", "Ignoring comment");
164                         continue;
165                     }
166                     //L(String.format("State is %d", updating));
167                     switch (state) {
168                         case EXPECTING_ACCOUNT:
169                             if (line.equals("<h2>General Journal</h2>")) {
170                                 state = ParserState.EXPECTING_TRANSACTION;
171                                 L("→ expecting transaction");
172                                 // commit the current transaction and start a new one
173                                 // the account list in the UI should reflect the (committed)
174                                 // state of the database
175                                 db.setTransactionSuccessful();
176                                 db.endTransaction();
177                                 Data.accounts.setList(accountList);
178                                 db.beginTransaction();
179                                 continue;
180                             }
181                             m = reAccountName.matcher(line);
182                             if (m.find()) {
183                                 String acct_encoded = m.group(1);
184                                 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
185                                 acct_name = acct_name.replace("\"", "");
186                                 L(String.format("found account: %s", acct_name));
187
188                                 prevAccount = lastAccount;
189                                 lastAccount = profile.tryLoadAccount(db, acct_name);
190                                 if (lastAccount == null) lastAccount = new LedgerAccount(acct_name);
191                                 else lastAccount.removeAmounts();
192                                 profile.storeAccount(db, lastAccount);
193
194                                 if (prevAccount != null) prevAccount
195                                         .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
196                                 // make sure the parent account(s) are present,
197                                 // synthesising them if necessary
198                                 // this happens when the (missing-in-HTML) parent account has
199                                 // only one child so we create a synthetic parent account record,
200                                 // copying the amounts when child's amounts are parsed
201                                 String parentName = lastAccount.getParentName();
202                                 if (parentName != null) {
203                                     Stack<String> toAppend = new Stack<>();
204                                     while (parentName != null) {
205                                         if (accountNames.containsKey(parentName)) break;
206                                         toAppend.push(parentName);
207                                         parentName = new LedgerAccount(parentName).getParentName();
208                                     }
209                                     syntheticAccounts.clear();
210                                     while (!toAppend.isEmpty()) {
211                                         String aName = toAppend.pop();
212                                         LedgerAccount acc = profile.tryLoadAccount(db, aName);
213                                         if (acc == null) {
214                                             acc = new LedgerAccount(aName);
215                                             acc.setHiddenByStar(lastAccount.isHiddenByStar());
216                                             acc.setExpanded(!lastAccount.hasSubAccounts() ||
217                                                             lastAccount.isExpanded());
218                                         }
219                                         acc.setHasSubAccounts(true);
220                                         acc.removeAmounts();    // filled below when amounts are parsed
221                                         if ((!onlyStarred || !acc.isHiddenByStar()) &&
222                                             acc.isVisible(accountList)) accountList.add(acc);
223                                         L(String.format("gap-filling with %s", aName));
224                                         accountNames.put(aName, null);
225                                         profile.storeAccount(db, acc);
226                                         syntheticAccounts.put(aName, acc);
227                                     }
228                                 }
229
230                                 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
231                                     lastAccount.isVisible(accountList))
232                                     accountList.add(lastAccount);
233                                 accountNames.put(acct_name, null);
234
235                                 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
236                                 L("→ expecting account amount");
237                             }
238                             break;
239
240                         case EXPECTING_ACCOUNT_AMOUNT:
241                             m = reAccountValue.matcher(line);
242                             boolean match_found = false;
243                             while (m.find()) {
244                                 throwIfCancelled();
245
246                                 match_found = true;
247                                 String value = m.group(1);
248                                 String currency = m.group(2);
249                                 if (currency == null) currency = "";
250
251                                 {
252                                     Matcher tmpM = reDecimalComma.matcher(value);
253                                     if (tmpM.find()) {
254                                         value = value.replace(".", "");
255                                         value = value.replace(',', '.');
256                                     }
257
258                                     tmpM = reDecimalPoint.matcher(value);
259                                     if (tmpM.find()) {
260                                         value = value.replace(",", "");
261                                         value = value.replace(" ", "");
262                                     }
263                                 }
264                                 L("curr=" + currency + ", value=" + value);
265                                 final float val = Float.parseFloat(value);
266                                 profile.storeAccountValue(db, lastAccount.getName(), currency, val);
267                                 lastAccount.addAmount(val, currency);
268                                 for (LedgerAccount syn : syntheticAccounts.values()) {
269                                     L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
270                                             currency, val, syn.getName()));
271                                     syn.addAmount(val, currency);
272                                     profile.storeAccountValue(db, syn.getName(), currency, val);
273                                 }
274                             }
275
276                             if (match_found) {
277                                 syntheticAccounts.clear();
278                                 state = ParserState.EXPECTING_ACCOUNT;
279                                 L("→ expecting account");
280                             }
281
282                             break;
283
284                         case EXPECTING_TRANSACTION:
285                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
286                             m = reTransactionStart.matcher(line);
287                             if (m.find()) {
288                                 transactionId = Integer.valueOf(m.group(1));
289                                 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
290                                 L(String.format(Locale.ENGLISH,
291                                         "found transaction %d → expecting description",
292                                         transactionId));
293                                 progress.setProgress(++processedTransactionCount);
294                                 if (maxTransactionId < transactionId)
295                                     maxTransactionId = transactionId;
296                                 if ((progress.getTotal() == Progress.INDETERMINATE) ||
297                                     (progress.getTotal() < transactionId))
298                                     progress.setTotal(transactionId);
299                                 publishProgress(progress);
300                             }
301                             m = reEnd.matcher(line);
302                             if (m.find()) {
303                                 L("--- transaction value complete ---");
304                                 break LINES;
305                             }
306                             break;
307
308                         case EXPECTING_TRANSACTION_DESCRIPTION:
309                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
310                             m = reTransactionDescription.matcher(line);
311                             if (m.find()) {
312                                 if (transactionId == 0) throw new TransactionParserException(
313                                         "Transaction Id is 0 while expecting " + "description");
314
315                                 String date = m.group(1);
316                                 try {
317                                     int equalsIndex = date.indexOf('=');
318                                     if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
319                                     transaction =
320                                             new LedgerTransaction(transactionId, date, m.group(2));
321                                 }
322                                 catch (ParseException e) {
323                                     e.printStackTrace();
324                                     return String.format("Error parsing date '%s'", date);
325                                 }
326                                 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
327                                 L(String.format(Locale.ENGLISH,
328                                         "transaction %d created for %s (%s) →" +
329                                         " expecting details", transactionId, date, m.group(2)));
330                             }
331                             break;
332
333                         case EXPECTING_TRANSACTION_DETAILS:
334                             if (line.isEmpty()) {
335                                 // transaction data collected
336                                 if (transaction.existsInDb(db)) {
337                                     profile.markTransactionAsPresent(db, transaction);
338                                     matchedTransactionsCount++;
339
340                                     if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
341                                         profile.markTransactionsBeforeTransactionAsPresent(db,
342                                                 transaction);
343                                         progress.setTotal(progress.getProgress());
344                                         publishProgress(progress);
345                                         break LINES;
346                                     }
347                                 }
348                                 else {
349                                     profile.storeTransaction(db, transaction);
350                                     matchedTransactionsCount = 0;
351                                     progress.setTotal(maxTransactionId);
352                                 }
353
354                                 state = ParserState.EXPECTING_TRANSACTION;
355                                 L(String.format("transaction %s saved → expecting transaction",
356                                         transaction.getId()));
357                                 transaction.finishLoading();
358
359 // sounds like a good idea, but transaction-1 may not be the first one chronologically
360 // for example, when you add the initial seeding transaction after entering some others
361 //                                            if (transactionId == 1) {
362 //                                                L("This was the initial transaction. Terminating " +
363 //                                                  "parser");
364 //                                                break LINES;
365 //                                            }
366                             }
367                             else {
368                                 m = reTransactionDetails.matcher(line);
369                                 if (m.find()) {
370                                     String acc_name = m.group(1);
371                                     String amount = m.group(2);
372                                     String currency = m.group(3);
373                                     if (currency == null) currency = "";
374                                     amount = amount.replace(',', '.');
375                                     transaction.addAccount(new LedgerTransactionAccount(acc_name,
376                                             Float.valueOf(amount), currency));
377                                     L(String.format(Locale.ENGLISH, "%d: %s = %s",
378                                             transaction.getId(), acc_name, amount));
379                                 }
380                                 else throw new IllegalStateException(
381                                         String.format("Can't parse transaction %d " + "details: %s",
382                                                 transactionId, line));
383                             }
384                             break;
385                         default:
386                             throw new RuntimeException(
387                                     String.format("Unknown parser updating %s", state.name()));
388                     }
389                 }
390
391                 throwIfCancelled();
392
393                 profile.deleteNotPresentTransactions(db);
394                 db.setTransactionSuccessful();
395
396                 profile.setLastUpdateStamp();
397
398                 return null;
399             }
400             finally {
401                 db.endTransaction();
402             }
403         }
404     }
405     private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
406         db.execSQL("UPDATE transactions set keep=0 where profile=?",
407                 new String[]{profile.getUuid()});
408         db.execSQL("update account_values set keep=0 where profile=?;",
409                 new String[]{profile.getUuid()});
410         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
411     }
412     private boolean retrieveAccountList() throws IOException, HTTPException {
413         Progress progress = new Progress();
414
415         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
416         http.setAllowUserInteraction(false);
417         switch (http.getResponseCode()) {
418             case 200:
419                 break;
420             case 404:
421                 return false;
422             default:
423                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
424         }
425         publishProgress(progress);
426         SQLiteDatabase db = App.getDatabase();
427         ArrayList<LedgerAccount> accountList = new ArrayList<>();
428         boolean listFilledOK = false;
429         try (InputStream resp = http.getInputStream()) {
430             if (http.getResponseCode() != 200)
431                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
432
433             db.beginTransaction();
434             try {
435                 profile.markAccountsAsNotPresent(db);
436
437                 AccountListParser parser = new AccountListParser(resp);
438
439                 LedgerAccount prevAccount = null;
440
441                 while (true) {
442                     throwIfCancelled();
443                     ParsedLedgerAccount parsedAccount = parser.nextAccount();
444                     if (parsedAccount == null) break;
445
446                     LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
447                     if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
448                     else acc.removeAmounts();
449
450                     profile.storeAccount(db, acc);
451                     String lastCurrency = null;
452                     float lastCurrencyAmount = 0;
453                     for (ParsedBalance b : parsedAccount.getAibalance()) {
454                         final String currency = b.getAcommodity();
455                         final float amount = b.getAquantity().asFloat();
456                         if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
457                         else {
458                             if (lastCurrency != null) {
459                                 profile.storeAccountValue(db, acc.getName(), lastCurrency,
460                                         lastCurrencyAmount);
461                                 acc.addAmount(lastCurrencyAmount, lastCurrency);
462                             }
463                             lastCurrency = currency;
464                             lastCurrencyAmount = amount;
465                         }
466                     }
467                     if (lastCurrency != null) {
468                         profile.storeAccountValue(db, acc.getName(), lastCurrency,
469                                 lastCurrencyAmount);
470                         acc.addAmount(lastCurrencyAmount, lastCurrency);
471                     }
472
473                     if (acc.isVisible(accountList)) accountList.add(acc);
474
475                     if (prevAccount != null) {
476                         prevAccount.setHasSubAccounts(
477                                 acc.getName().startsWith(prevAccount.getName() + ":"));
478                     }
479
480                     prevAccount = acc;
481                 }
482                 throwIfCancelled();
483
484                 profile.deleteNotPresentAccounts(db);
485                 throwIfCancelled();
486                 db.setTransactionSuccessful();
487                 listFilledOK = true;
488             }
489             finally {
490                 db.endTransaction();
491             }
492         }
493         // should not be set in the DB transaction, because of a possible deadlock
494         // with the main and DbOpQueueRunner threads
495         if (listFilledOK) Data.accounts.setList(accountList);
496
497         return true;
498     }
499     private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
500         Progress progress = new Progress();
501         int maxTransactionId = Progress.INDETERMINATE;
502
503         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
504         http.setAllowUserInteraction(false);
505         publishProgress(progress);
506         switch (http.getResponseCode()) {
507             case 200:
508                 break;
509             case 404:
510                 return false;
511             default:
512                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
513         }
514         SQLiteDatabase db = App.getDatabase();
515         try (InputStream resp = http.getInputStream()) {
516             if (http.getResponseCode() != 200)
517                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
518             throwIfCancelled();
519             db.beginTransaction();
520             try {
521                 profile.markTransactionsAsNotPresent(db);
522
523                 int matchedTransactionsCount = 0;
524                 TransactionListParser parser = new TransactionListParser(resp);
525
526                 int processedTransactionCount = 0;
527
528                 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
529                 int orderAccumulator = 0;
530                 int lastTransactionId = 0;
531
532                 while (true) {
533                     throwIfCancelled();
534                     ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
535                     throwIfCancelled();
536                     if (parsedTransaction == null) break;
537
538                     LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
539                     if (transaction.getId() > lastTransactionId) orderAccumulator++;
540                     else orderAccumulator--;
541                     lastTransactionId = transaction.getId();
542                     if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
543                         if (orderAccumulator > 30) {
544                             transactionOrder = DetectedTransactionOrder.FILE;
545                             debug("rtt", String.format(Locale.ENGLISH,
546                                     "Detected native file order after %d transactions (factor %d)",
547                                     processedTransactionCount, orderAccumulator));
548                             progress.setTotal(Data.transactions.size());
549                         }
550                         else if (orderAccumulator < -30) {
551                             transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
552                             debug("rtt", String.format(Locale.ENGLISH,
553                                     "Detected reverse chronological order after %d transactions (factor %d)",
554                                     processedTransactionCount, orderAccumulator));
555                         }
556                     }
557
558                     if (transaction.existsInDb(db)) {
559                         profile.markTransactionAsPresent(db, transaction);
560                         matchedTransactionsCount++;
561
562                         if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
563                             (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
564                         {
565                             profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
566                             progress.setTotal(progress.getProgress());
567                             publishProgress(progress);
568                             db.setTransactionSuccessful();
569                             profile.setLastUpdateStamp();
570                             return true;
571                         }
572                     }
573                     else {
574                         profile.storeTransaction(db, transaction);
575                         matchedTransactionsCount = 0;
576                         progress.setTotal(maxTransactionId);
577                     }
578
579
580                     if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
581                         ((progress.getTotal() == Progress.INDETERMINATE) ||
582                          (progress.getTotal() < transaction.getId())))
583                         progress.setTotal(transaction.getId());
584
585                     progress.setProgress(++processedTransactionCount);
586                     publishProgress(progress);
587                 }
588
589                 throwIfCancelled();
590                 profile.deleteNotPresentTransactions(db);
591                 throwIfCancelled();
592                 db.setTransactionSuccessful();
593                 profile.setLastUpdateStamp();
594             }
595             finally {
596                 db.endTransaction();
597             }
598         }
599
600         return true;
601     }
602
603     @SuppressLint("DefaultLocale")
604     @Override
605     protected String doInBackground(Void... params) {
606         Data.backgroundTaskStarted();
607         try {
608             if (!retrieveAccountList() || !retrieveTransactionList())
609                 return retrieveTransactionListLegacy();
610             return null;
611         }
612         catch (MalformedURLException e) {
613             e.printStackTrace();
614             return "Invalid server URL";
615         }
616         catch (HTTPException e) {
617             e.printStackTrace();
618             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
619         }
620         catch (IOException e) {
621             e.printStackTrace();
622             return e.getLocalizedMessage();
623         }
624         catch (ParseException e) {
625             e.printStackTrace();
626             return "Network error";
627         }
628         catch (OperationCanceledException e) {
629             e.printStackTrace();
630             return "Operation cancelled";
631         }
632         finally {
633             Data.backgroundTaskFinished();
634         }
635     }
636     private MainActivity getContext() {
637         return contextRef.get();
638     }
639     private void throwIfCancelled() {
640         if (isCancelled()) throw new OperationCanceledException(null);
641     }
642     enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
643
644     private enum ParserState {
645         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
646         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
647     }
648
649     public class Progress {
650         public static final int INDETERMINATE = -1;
651         private int progress;
652         private int total;
653         Progress() {
654             this(INDETERMINATE, INDETERMINATE);
655         }
656         Progress(int progress, int total) {
657             this.progress = progress;
658             this.total = total;
659         }
660         public int getProgress() {
661             return progress;
662         }
663         protected void setProgress(int progress) {
664             this.progress = progress;
665         }
666         public int getTotal() {
667             return total;
668         }
669         protected void setTotal(int total) {
670             this.total = total;
671         }
672     }
673
674     private class TransactionParserException extends IllegalStateException {
675         TransactionParserException(String message) {
676             super(message);
677         }
678     }
679 }