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