]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
profile should not be null when requesting transaction retrieval
[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.App;
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.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 androidx.annotation.NonNull;
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 WeakReference<MainActivity> contextRef;
74     // %3A is '='
75     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
76     private Pattern reAccountValue = Pattern.compile(
77             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
78     private MobileLedgerProfile profile;
79     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
80                                     @NonNull MobileLedgerProfile profile) {
81         this.contextRef = contextRef;
82         this.profile = profile;
83     }
84     private static void L(String msg) {
85         //debug("transaction-parser", msg);
86     }
87     @Override
88     protected void onProgressUpdate(Progress... values) {
89         super.onProgressUpdate(values);
90         MainActivity context = getContext();
91         if (context == null) return;
92         context.onRetrieveProgress(values[0]);
93     }
94     @Override
95     protected void onPreExecute() {
96         super.onPreExecute();
97         MainActivity context = getContext();
98         if (context == null) return;
99         context.onRetrieveStart();
100     }
101     @Override
102     protected void onPostExecute(String error) {
103         super.onPostExecute(error);
104         MainActivity context = getContext();
105         if (context == null) return;
106         context.onRetrieveDone(error);
107     }
108     @Override
109     protected void onCancelled() {
110         super.onCancelled();
111         MainActivity context = getContext();
112         if (context == null) return;
113         context.onRetrieveDone(null);
114     }
115     private String retrieveTransactionListLegacy()
116             throws IOException, ParseException, HTTPException {
117         Progress progress = new Progress();
118         int maxTransactionId = Progress.INDETERMINATE;
119         ArrayList<LedgerAccount> accountList = new ArrayList<>();
120         HashMap<String, Void> accountNames = new HashMap<>();
121         HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
122         LedgerAccount lastAccount = null, prevAccount = null;
123         boolean onlyStarred = Data.optShowOnlyStarred.get();
124
125         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
126         http.setAllowUserInteraction(false);
127         publishProgress(progress);
128         switch (http.getResponseCode()) {
129             case 200:
130                 break;
131             default:
132                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
133         }
134
135         SQLiteDatabase db = App.getDatabase();
136         try (InputStream resp = http.getInputStream()) {
137             if (http.getResponseCode() != 200)
138                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
139             db.beginTransaction();
140             try {
141                 prepareDbForRetrieval(db, profile);
142
143                 int matchedTransactionsCount = 0;
144
145
146                 ParserState state = ParserState.EXPECTING_ACCOUNT;
147                 String line;
148                 BufferedReader buf =
149                         new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
150
151                 int processedTransactionCount = 0;
152                 int transactionId = 0;
153                 LedgerTransaction transaction = null;
154                 LINES:
155                 while ((line = buf.readLine()) != null) {
156                     throwIfCancelled();
157                     Matcher m;
158                     m = reComment.matcher(line);
159                     if (m.find()) {
160                         // TODO: comments are ignored for now
161 //                            Log.v("transaction-parser", "Ignoring comment");
162                         continue;
163                     }
164                     //L(String.format("State is %d", updating));
165                     switch (state) {
166                         case EXPECTING_ACCOUNT:
167                             if (line.equals("<h2>General Journal</h2>")) {
168                                 state = ParserState.EXPECTING_TRANSACTION;
169                                 L("→ expecting transaction");
170                                 // commit the current transaction and start a new one
171                                 // the account list in the UI should reflect the (committed)
172                                 // state of the database
173                                 db.setTransactionSuccessful();
174                                 db.endTransaction();
175                                 Data.accounts.setList(accountList);
176                                 db.beginTransaction();
177                                 continue;
178                             }
179                             m = reAccountName.matcher(line);
180                             if (m.find()) {
181                                 String acct_encoded = m.group(1);
182                                 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
183                                 acct_name = acct_name.replace("\"", "");
184                                 L(String.format("found account: %s", acct_name));
185
186                                 prevAccount = lastAccount;
187                                 lastAccount = profile.tryLoadAccount(db, acct_name);
188                                 if (lastAccount == null) lastAccount = new LedgerAccount(acct_name);
189                                 else lastAccount.removeAmounts();
190                                 profile.storeAccount(db, lastAccount);
191
192                                 if (prevAccount != null) prevAccount
193                                         .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
194                                 // make sure the parent account(s) are present,
195                                 // synthesising them if necessary
196                                 // this happens when the (missing-in-HTML) parent account has
197                                 // only one child so we create a synthetic parent account record,
198                                 // copying the amounts when child's amounts are parsed
199                                 String parentName = lastAccount.getParentName();
200                                 if (parentName != null) {
201                                     Stack<String> toAppend = new Stack<>();
202                                     while (parentName != null) {
203                                         if (accountNames.containsKey(parentName)) break;
204                                         toAppend.push(parentName);
205                                         parentName = new LedgerAccount(parentName).getParentName();
206                                     }
207                                     syntheticAccounts.clear();
208                                     while (!toAppend.isEmpty()) {
209                                         String aName = toAppend.pop();
210                                         LedgerAccount acc = profile.tryLoadAccount(db, aName);
211                                         if (acc == null) {
212                                             acc = new LedgerAccount(aName);
213                                             acc.setHiddenByStar(lastAccount.isHiddenByStar());
214                                             acc.setExpanded(!lastAccount.hasSubAccounts() ||
215                                                             lastAccount.isExpanded());
216                                         }
217                                         acc.setHasSubAccounts(true);
218                                         acc.removeAmounts();    // filled below when amounts are parsed
219                                         if ((!onlyStarred || !acc.isHiddenByStar()) &&
220                                             acc.isVisible(accountList)) accountList.add(acc);
221                                         L(String.format("gap-filling with %s", aName));
222                                         accountNames.put(aName, null);
223                                         profile.storeAccount(db, acc);
224                                         syntheticAccounts.put(aName, acc);
225                                     }
226                                 }
227
228                                 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
229                                     lastAccount.isVisible(accountList))
230                                     accountList.add(lastAccount);
231                                 accountNames.put(acct_name, null);
232
233                                 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
234                                 L("→ expecting account amount");
235                             }
236                             break;
237
238                         case EXPECTING_ACCOUNT_AMOUNT:
239                             m = reAccountValue.matcher(line);
240                             boolean match_found = false;
241                             while (m.find()) {
242                                 throwIfCancelled();
243
244                                 match_found = true;
245                                 String value = m.group(1);
246                                 String currency = m.group(2);
247                                 if (currency == null) currency = "";
248                                 value = value.replace(',', '.');
249                                 L("curr=" + currency + ", value=" + value);
250                                 final float val = Float.parseFloat(value);
251                                 profile.storeAccountValue(db, lastAccount.getName(), currency, 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) date = date.substring(equalsIndex + 1);
301                                     transaction =
302                                             new LedgerTransaction(transactionId, date, m.group(2));
303                                 }
304                                 catch (ParseException e) {
305                                     e.printStackTrace();
306                                     return String.format("Error parsing date '%s'", date);
307                                 }
308                                 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
309                                 L(String.format(Locale.ENGLISH,
310                                         "transaction %d created for %s (%s) →" +
311                                         " expecting details", transactionId, date, m.group(2)));
312                             }
313                             break;
314
315                         case EXPECTING_TRANSACTION_DETAILS:
316                             if (line.isEmpty()) {
317                                 // transaction data collected
318                                 if (transaction.existsInDb(db)) {
319                                     profile.markTransactionAsPresent(db, transaction);
320                                     matchedTransactionsCount++;
321
322                                     if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
323                                         profile.markTransactionsBeforeTransactionAsPresent(db,
324                                                 transaction);
325                                         progress.setTotal(progress.getProgress());
326                                         publishProgress(progress);
327                                         break LINES;
328                                     }
329                                 }
330                                 else {
331                                     profile.storeTransaction(db, transaction);
332                                     matchedTransactionsCount = 0;
333                                     progress.setTotal(maxTransactionId);
334                                 }
335
336                                 state = ParserState.EXPECTING_TRANSACTION;
337                                 L(String.format("transaction %s saved → expecting transaction",
338                                         transaction.getId()));
339                                 transaction.finishLoading();
340
341 // sounds like a good idea, but transaction-1 may not be the first one chronologically
342 // for example, when you add the initial seeding transaction after entering some others
343 //                                            if (transactionId == 1) {
344 //                                                L("This was the initial transaction. Terminating " +
345 //                                                  "parser");
346 //                                                break LINES;
347 //                                            }
348                             }
349                             else {
350                                 m = reTransactionDetails.matcher(line);
351                                 if (m.find()) {
352                                     String acc_name = m.group(1);
353                                     String amount = m.group(2);
354                                     String currency = m.group(3);
355                                     if (currency == null) currency = "";
356                                     amount = amount.replace(',', '.');
357                                     transaction.addAccount(new LedgerTransactionAccount(acc_name,
358                                             Float.valueOf(amount), currency));
359                                     L(String.format(Locale.ENGLISH, "%d: %s = %s",
360                                             transaction.getId(), acc_name, amount));
361                                 }
362                                 else throw new IllegalStateException(
363                                         String.format("Can't parse transaction %d " + "details: %s",
364                                                 transactionId, line));
365                             }
366                             break;
367                         default:
368                             throw new RuntimeException(
369                                     String.format("Unknown parser updating %s", state.name()));
370                     }
371                 }
372
373                 throwIfCancelled();
374
375                 profile.deleteNotPresentTransactions(db);
376                 db.setTransactionSuccessful();
377
378                 profile.setLastUpdateStamp();
379
380                 return null;
381             }
382             finally {
383                 db.endTransaction();
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()
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 = App.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()
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 = App.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                             debug("rtt", String.format(Locale.ENGLISH,
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                             debug("rtt", String.format(Locale.ENGLISH,
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         Data.backgroundTaskStarted();
591         try {
592             if (!retrieveAccountList() || !retrieveTransactionList())
593                 return retrieveTransactionListLegacy();
594             return null;
595         }
596         catch (MalformedURLException e) {
597             e.printStackTrace();
598             return "Invalid server URL";
599         }
600         catch (HTTPException e) {
601             e.printStackTrace();
602             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
603         }
604         catch (IOException e) {
605             e.printStackTrace();
606             return e.getLocalizedMessage();
607         }
608         catch (ParseException e) {
609             e.printStackTrace();
610             return "Network error";
611         }
612         catch (OperationCanceledException e) {
613             e.printStackTrace();
614             return "Operation cancelled";
615         }
616         finally {
617             Data.backgroundTaskFinished();
618         }
619     }
620     private MainActivity getContext() {
621         return contextRef.get();
622     }
623     private void throwIfCancelled() {
624         if (isCancelled()) throw new OperationCanceledException(null);
625     }
626     enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
627
628     private enum ParserState {
629         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
630         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
631     }
632
633     public class Progress {
634         public static final int INDETERMINATE = -1;
635         private int progress;
636         private int total;
637         Progress() {
638             this(INDETERMINATE, INDETERMINATE);
639         }
640         Progress(int progress, int total) {
641             this.progress = progress;
642             this.total = total;
643         }
644         public int getProgress() {
645             return progress;
646         }
647         protected void setProgress(int progress) {
648             this.progress = progress;
649         }
650         public int getTotal() {
651             return total;
652         }
653         protected void setTotal(int total) {
654             this.total = total;
655         }
656     }
657
658     private class TransactionParserException extends IllegalStateException {
659         TransactionParserException(String message) {
660             super(message);
661         }
662     }
663 }