]> git.ktnx.net Git - mobile-ledger.git/blobdiff - app/src/main/java/net/ktnx/mobileledger/async/SendTransactionTask.java
more pronounced day/month delimiters in the transaction list
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / SendTransactionTask.java
index 14d41f9f14a9bffeef548d94b264db5382628b20..0e700cca9a510be8e210fafccbe548b88c2a427a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2020 Damyan Ivanov.
+ * Copyright © 2023 Damyan Ivanov.
  * This file is part of MoLe.
  * MoLe is free software: you can distribute it and/or modify it
  * under the term of the GNU General Public License as published by
 
 package net.ktnx.mobileledger.async;
 
-import android.os.AsyncTask;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
 import android.util.Log;
 
+import net.ktnx.mobileledger.db.Profile;
 import net.ktnx.mobileledger.json.API;
+import net.ktnx.mobileledger.json.ApiNotSupportedException;
 import net.ktnx.mobileledger.json.Gateway;
 import net.ktnx.mobileledger.model.LedgerTransaction;
 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
-import net.ktnx.mobileledger.model.MobileLedgerProfile;
 import net.ktnx.mobileledger.utils.Globals;
 import net.ktnx.mobileledger.utils.Logger;
+import net.ktnx.mobileledger.utils.Misc;
 import net.ktnx.mobileledger.utils.NetworkUtil;
 import net.ktnx.mobileledger.utils.SimpleDate;
 import net.ktnx.mobileledger.utils.UrlEncodedFormData;
@@ -44,36 +47,29 @@ import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-import static android.os.SystemClock.sleep;
-import static net.ktnx.mobileledger.utils.Logger.debug;
-
 /* TODO: get rid of the custom session/cookie and auth code?
  *       (the last problem with the POST was the missing content-length header)
  *       This will resolve itself when hledger-web 1.14+ is released with Debian/stable,
  *       at which point the HTML form emulation can be dropped entirely
  */
 
-public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
+public class SendTransactionTask extends Thread {
     private final TaskCallback taskCallback;
-    private final MobileLedgerProfile mProfile;
+    private final Profile mProfile;
     private final boolean simulate;
+    private final LedgerTransaction transaction;
     protected String error;
     private String token;
     private String session;
-    private LedgerTransaction transaction;
 
-    public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile,
-                               boolean simulate) {
+    public SendTransactionTask(TaskCallback callback, Profile profile,
+                               LedgerTransaction transaction, boolean simulate) {
         taskCallback = callback;
         mProfile = profile;
+        this.transaction = transaction;
         this.simulate = simulate;
     }
-    public SendTransactionTask(TaskCallback callback, MobileLedgerProfile profile) {
-        taskCallback = callback;
-        mProfile = profile;
-        simulate = false;
-    }
-    private boolean sendOK(API apiVersion) throws IOException {
+    private void sendOK(API apiVersion) throws IOException, ApiNotSupportedException {
         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
         http.setRequestMethod("PUT");
         http.setRequestProperty("Content-Type", "application/json");
@@ -82,9 +78,11 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
         Gateway gateway = Gateway.forApiVersion(apiVersion);
         String body = gateway.transactionSaveRequest(transaction);
 
-        return sendRequest(http, body);
+        Logger.debug("network", "Sending using API " + apiVersion);
+        sendRequest(http, body);
     }
-    private boolean sendRequest(HttpURLConnection http, String body) throws IOException {
+    private void sendRequest(HttpURLConnection http, String body)
+            throws IOException, ApiNotSupportedException {
         if (simulate) {
             debug("network", "The request would be: " + body);
             try {
@@ -96,7 +94,7 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
                 Logger.debug("network", ex.toString());
             }
 
-            return true;
+            return;
         }
 
         byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
@@ -124,16 +122,21 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
                     case 400:
                     case 405: {
                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
-                        String line;
+                        StringBuilder errorLines = new StringBuilder();
                         int count = 0;
                         while (count <= 5) {
-                            line = reader.readLine();
+                            String line = reader.readLine();
                             if (line == null)
                                 break;
                             Logger.debug("network", line);
+
+                            if (errorLines.length() != 0)
+                                errorLines.append("\n");
+
+                            errorLines.append(line);
                             count++;
                         }
-                        return false; // will cause a retry with another method
+                        throw new ApiNotSupportedException(errorLines.toString());
                     }
                     default:
                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
@@ -144,8 +147,6 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
                 }
             }
         }
-
-        return true;
     }
     private boolean legacySendOK() throws IOException {
         HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
@@ -242,24 +243,27 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
         }
     }
     @Override
-    protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
+    public void run() {
         error = null;
         try {
-            transaction = ledgerTransactions[0];
-
-            final API profileApiVersion = mProfile.getApiVersion();
+            final API profileApiVersion = API.valueOf(mProfile.getApiVersion());
             switch (profileApiVersion) {
                 case auto:
                     boolean sendOK = false;
                     for (API ver : API.allVersions) {
                         Logger.debug("network", "Trying version " + ver);
-                        if (sendOK(ver)) {
+                        try {
+                            sendOK(ver);
                             sendOK = true;
                             Logger.debug("network", "Version " + ver + " request succeeded");
 
                             break;
                         }
+                        catch (ApiNotSupportedException e) {
+                            Logger.debug("network", "Version " + ver + " seems not supported");
+                        }
                     }
+
                     if (!sendOK) {
                         Logger.debug("network", "Trying HTML form emulation");
                         legacySendOkWithRetry();
@@ -271,18 +275,19 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
                 case v1_14:
                 case v1_15:
                 case v1_19_1:
+                case v1_23:
                     sendOK(profileApiVersion);
                     break;
                 default:
                     throw new IllegalStateException("Unexpected API version: " + profileApiVersion);
             }
         }
-        catch (Exception e) {
+        catch (ApiNotSupportedException | Exception e) {
             e.printStackTrace();
             error = e.getMessage();
         }
 
-        return null;
+        Misc.onMainThread(() -> taskCallback.onTransactionSaveDone(error, transaction));
     }
     private void legacySendOkWithRetry() throws IOException {
         int tried = 0;
@@ -290,13 +295,13 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
             tried++;
             if (tried >= 2)
                 throw new IOException(String.format("aborting after %d tries", tried));
-            sleep(100);
+            try {
+                sleep(100);
+            }
+            catch (InterruptedException e) {
+                e.printStackTrace();
+                break;
+            }
         }
     }
-    @Override
-    protected void onPostExecute(Void aVoid) {
-        super.onPostExecute(aVoid);
-        taskCallback.done(error);
-    }
-
 }
\ No newline at end of file