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