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