]> git.ktnx.net Git - mobile-ledger.git/blob - async/RetrieveTransactionsTask.java
bump androidx.constraintlayout library version
[mobile-ledger.git] / 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                                     L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
255                                             currency, val, syn.getName()));
256                                     syn.addAmount(val, currency);
257                                     profile.storeAccountValue(db, syn.getName(), currency, val);
258                                 }
259                             }
260
261                             if (match_found) {
262                                 syntheticAccounts.clear();
263                                 state = ParserState.EXPECTING_ACCOUNT;
264                                 L("→ expecting account");
265                             }
266
267                             break;
268
269                         case EXPECTING_TRANSACTION:
270                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
271                             m = reTransactionStart.matcher(line);
272                             if (m.find()) {
273                                 transactionId = Integer.valueOf(m.group(1));
274                                 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
275                                 L(String.format(Locale.ENGLISH,
276                                         "found transaction %d → expecting description",
277                                         transactionId));
278                                 progress.setProgress(++processedTransactionCount);
279                                 if (maxTransactionId < transactionId)
280                                     maxTransactionId = transactionId;
281                                 if ((progress.getTotal() == Progress.INDETERMINATE) ||
282                                     (progress.getTotal() < transactionId))
283                                     progress.setTotal(transactionId);
284                                 publishProgress(progress);
285                             }
286                             m = reEnd.matcher(line);
287                             if (m.find()) {
288                                 L("--- transaction value complete ---");
289                                 break LINES;
290                             }
291                             break;
292
293                         case EXPECTING_TRANSACTION_DESCRIPTION:
294                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
295                             m = reTransactionDescription.matcher(line);
296                             if (m.find()) {
297                                 if (transactionId == 0) throw new TransactionParserException(
298                                         "Transaction Id is 0 while expecting " + "description");
299
300                                 String date = m.group(1);
301                                 try {
302                                     int equalsIndex = date.indexOf('=');
303                                     if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
304                                     transaction =
305                                             new LedgerTransaction(transactionId, date, m.group(2));
306                                 }
307                                 catch (ParseException e) {
308                                     e.printStackTrace();
309                                     return String.format("Error parsing date '%s'", date);
310                                 }
311                                 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
312                                 L(String.format(Locale.ENGLISH,
313                                         "transaction %d created for %s (%s) →" +
314                                         " expecting details", transactionId, date, m.group(2)));
315                             }
316                             break;
317
318                         case EXPECTING_TRANSACTION_DETAILS:
319                             if (line.isEmpty()) {
320                                 // transaction data collected
321                                 if (transaction.existsInDb(db)) {
322                                     profile.markTransactionAsPresent(db, transaction);
323                                     matchedTransactionsCount++;
324
325                                     if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
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(new LedgerTransactionAccount(acc_name,
361                                             Float.valueOf(amount), currency));
362                                     L(String.format(Locale.ENGLISH, "%d: %s = %s",
363                                             transaction.getId(), acc_name, amount));
364                                 }
365                                 else throw new IllegalStateException(
366                                         String.format("Can't parse transaction %d " + "details: %s",
367                                                 transactionId, line));
368                             }
369                             break;
370                         default:
371                             throw new RuntimeException(
372                                     String.format("Unknown parser updating %s", state.name()));
373                     }
374                 }
375
376                 throwIfCancelled();
377
378                 profile.deleteNotPresentTransactions(db);
379                 db.setTransactionSuccessful();
380
381                 profile.setLastUpdateStamp();
382
383                 return null;
384             }
385             finally {
386                 db.endTransaction();
387             }
388         }
389     }
390     private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
391         db.execSQL("UPDATE transactions set keep=0 where profile=?",
392                 new String[]{profile.getUuid()});
393         db.execSQL("update account_values set keep=0 where profile=?;",
394                 new String[]{profile.getUuid()});
395         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
396     }
397     private boolean retrieveAccountList() throws IOException, HTTPException {
398         Progress progress = new Progress();
399
400         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
401         http.setAllowUserInteraction(false);
402         switch (http.getResponseCode()) {
403             case 200:
404                 break;
405             case 404:
406                 return false;
407             default:
408                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
409         }
410         publishProgress(progress);
411         SQLiteDatabase db = App.getDatabase();
412         ArrayList<LedgerAccount> accountList = new ArrayList<>();
413         boolean listFilledOK = false;
414         try (InputStream resp = http.getInputStream()) {
415             if (http.getResponseCode() != 200)
416                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
417
418             db.beginTransaction();
419             try {
420                 profile.markAccountsAsNotPresent(db);
421
422                 AccountListParser parser = new AccountListParser(resp);
423
424                 LedgerAccount prevAccount = null;
425
426                 while (true) {
427                     throwIfCancelled();
428                     ParsedLedgerAccount parsedAccount = parser.nextAccount();
429                     if (parsedAccount == null) break;
430
431                     LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
432                     if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
433                     else acc.removeAmounts();
434
435                     profile.storeAccount(db, acc);
436                     String lastCurrency = null;
437                     float lastCurrencyAmount = 0;
438                     for (ParsedBalance b : parsedAccount.getAibalance()) {
439                         final String currency = b.getAcommodity();
440                         final float amount = b.getAquantity().asFloat();
441                         if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
442                         else {
443                             if (lastCurrency != null) {
444                                 profile.storeAccountValue(db, acc.getName(), lastCurrency,
445                                         lastCurrencyAmount);
446                                 acc.addAmount(lastCurrencyAmount, lastCurrency);
447                             }
448                             lastCurrency = currency;
449                             lastCurrencyAmount = amount;
450                         }
451                     }
452                     if (lastCurrency != null) {
453                         profile.storeAccountValue(db, acc.getName(), lastCurrency,
454                                 lastCurrencyAmount);
455                         acc.addAmount(lastCurrencyAmount, lastCurrency);
456                     }
457
458                     if (acc.isVisible(accountList)) accountList.add(acc);
459
460                     if (prevAccount != null) {
461                         prevAccount.setHasSubAccounts(
462                                 acc.getName().startsWith(prevAccount.getName() + ":"));
463                     }
464
465                     prevAccount = acc;
466                 }
467                 throwIfCancelled();
468
469                 profile.deleteNotPresentAccounts(db);
470                 throwIfCancelled();
471                 db.setTransactionSuccessful();
472                 listFilledOK = true;
473             }
474             finally {
475                 db.endTransaction();
476             }
477         }
478         // should not be set in the DB transaction, because of a possible deadlock
479         // with the main and DbOpQueueRunner threads
480         if (listFilledOK) Data.accounts.setList(accountList);
481
482         return true;
483     }
484     private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
485         Progress progress = new Progress();
486         int maxTransactionId = Progress.INDETERMINATE;
487
488         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
489         http.setAllowUserInteraction(false);
490         publishProgress(progress);
491         switch (http.getResponseCode()) {
492             case 200:
493                 break;
494             case 404:
495                 return false;
496             default:
497                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
498         }
499         SQLiteDatabase db = App.getDatabase();
500         try (InputStream resp = http.getInputStream()) {
501             if (http.getResponseCode() != 200)
502                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
503             throwIfCancelled();
504             db.beginTransaction();
505             try {
506                 profile.markTransactionsAsNotPresent(db);
507
508                 int matchedTransactionsCount = 0;
509                 TransactionListParser parser = new TransactionListParser(resp);
510
511                 int processedTransactionCount = 0;
512
513                 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
514                 int orderAccumulator = 0;
515                 int lastTransactionId = 0;
516
517                 while (true) {
518                     throwIfCancelled();
519                     ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
520                     throwIfCancelled();
521                     if (parsedTransaction == null) break;
522
523                     LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
524                     if (transaction.getId() > lastTransactionId) orderAccumulator++;
525                     else orderAccumulator--;
526                     lastTransactionId = transaction.getId();
527                     if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
528                         if (orderAccumulator > 30) {
529                             transactionOrder = DetectedTransactionOrder.FILE;
530                             debug("rtt", String.format(Locale.ENGLISH,
531                                     "Detected native file order after %d transactions (factor %d)",
532                                     processedTransactionCount, orderAccumulator));
533                             progress.setTotal(Data.transactions.size());
534                         }
535                         else if (orderAccumulator < -30) {
536                             transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
537                             debug("rtt", String.format(Locale.ENGLISH,
538                                     "Detected reverse chronological order after %d transactions (factor %d)",
539                                     processedTransactionCount, orderAccumulator));
540                         }
541                     }
542
543                     if (transaction.existsInDb(db)) {
544                         profile.markTransactionAsPresent(db, transaction);
545                         matchedTransactionsCount++;
546
547                         if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
548                             (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
549                         {
550                             profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
551                             progress.setTotal(progress.getProgress());
552                             publishProgress(progress);
553                             db.setTransactionSuccessful();
554                             profile.setLastUpdateStamp();
555                             return true;
556                         }
557                     }
558                     else {
559                         profile.storeTransaction(db, transaction);
560                         matchedTransactionsCount = 0;
561                         progress.setTotal(maxTransactionId);
562                     }
563
564
565                     if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
566                         ((progress.getTotal() == Progress.INDETERMINATE) ||
567                          (progress.getTotal() < transaction.getId())))
568                         progress.setTotal(transaction.getId());
569
570                     progress.setProgress(++processedTransactionCount);
571                     publishProgress(progress);
572                 }
573
574                 throwIfCancelled();
575                 profile.deleteNotPresentTransactions(db);
576                 throwIfCancelled();
577                 db.setTransactionSuccessful();
578                 profile.setLastUpdateStamp();
579             }
580             finally {
581                 db.endTransaction();
582             }
583         }
584
585         return true;
586     }
587
588     @SuppressLint("DefaultLocale")
589     @Override
590     protected String doInBackground(Void... params) {
591         Data.backgroundTaskStarted();
592         try {
593             if (!retrieveAccountList() || !retrieveTransactionList())
594                 return retrieveTransactionListLegacy();
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 }