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