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