]> 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 fa69f86c593fbacaa65de813d457a2eaa5db056d..0e700cca9a510be8e210fafccbe548b88c2a427a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2019 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 android.util.Log;
+import static net.ktnx.mobileledger.utils.Logger.debug;
 
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
+import android.util.Log;
 
-import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
-import net.ktnx.mobileledger.model.Data;
+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.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;
 
 import java.io.BufferedReader;
@@ -44,44 +47,71 @@ import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-import static android.os.SystemClock.sleep;
+/* 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 Profile mProfile;
+    private final boolean simulate;
+    private final LedgerTransaction transaction;
     protected String error;
     private String token;
     private String session;
-    private LedgerTransaction ltr;
 
-    public SendTransactionTask(TaskCallback callback) {
+    public SendTransactionTask(TaskCallback callback, Profile profile,
+                               LedgerTransaction transaction, boolean simulate) {
         taskCallback = callback;
+        mProfile = profile;
+        this.transaction = transaction;
+        this.simulate = simulate;
     }
-    private boolean sendOK() throws IOException {
-        HttpURLConnection http = NetworkUtil.prepareConnection(Data.profile.get(), "add");
+    private void sendOK(API apiVersion) throws IOException, ApiNotSupportedException {
+        HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
         http.setRequestMethod("PUT");
         http.setRequestProperty("Content-Type", "application/json");
         http.setRequestProperty("Accept", "*/*");
 
-        ParsedLedgerTransaction jsonTransaction;
-        jsonTransaction = ltr.toParsedLedgerTransaction();
-        ObjectMapper mapper = new ObjectMapper();
-        ObjectWriter writer = mapper.writerFor(ParsedLedgerTransaction.class);
-        String body = writer.writeValueAsString(jsonTransaction);
+        Gateway gateway = Gateway.forApiVersion(apiVersion);
+        String body = gateway.transactionSaveRequest(transaction);
+
+        Logger.debug("network", "Sending using API " + apiVersion);
+        sendRequest(http, body);
+    }
+    private void sendRequest(HttpURLConnection http, String body)
+            throws IOException, ApiNotSupportedException {
+        if (simulate) {
+            debug("network", "The request would be: " + body);
+            try {
+                Thread.sleep(1500);
+                if (Math.random() > 0.3)
+                    throw new RuntimeException("Simulated test exception");
+            }
+            catch (InterruptedException ex) {
+                Logger.debug("network", ex.toString());
+            }
+
+            return;
+        }
 
         byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
         http.setDoOutput(true);
         http.setDoInput(true);
         http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
 
-        Log.d("network", "request header: " + http.getRequestProperties().toString());
+        debug("network", "request header: " + http.getRequestProperties()
+                                                  .toString());
 
         try (OutputStream req = http.getOutputStream()) {
-            Log.d("network", "Request body: " + body);
+            debug("network", "Request body: " + body);
             req.write(bodyBytes);
 
             final int responseCode = http.getResponseCode();
-            Log.d("network",
-                    String.format("Response: %d %s", responseCode, http.getResponseMessage()));
+            debug("network", String.format(Locale.US, "Response: %d %s", responseCode,
+                    http.getResponseMessage()));
 
             try (InputStream resp = http.getErrorStream()) {
 
@@ -89,22 +119,37 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
                     case 200:
                     case 201:
                         break;
-                    case 405:
-                        return false; // will cause a retry with the legacy method
+                    case 400:
+                    case 405: {
+                        BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
+                        StringBuilder errorLines = new StringBuilder();
+                        int count = 0;
+                        while (count <= 5) {
+                            String line = reader.readLine();
+                            if (line == null)
+                                break;
+                            Logger.debug("network", line);
+
+                            if (errorLines.length() != 0)
+                                errorLines.append("\n");
+
+                            errorLines.append(line);
+                            count++;
+                        }
+                        throw new ApiNotSupportedException(errorLines.toString());
+                    }
                     default:
                         BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
                         String line = reader.readLine();
-                        Log.d("network", "Response content: " + line);
+                        debug("network", "Response content: " + line);
                         throw new IOException(
                                 String.format("Error response code %d", responseCode));
                 }
             }
         }
-
-        return true;
     }
     private boolean legacySendOK() throws IOException {
-        HttpURLConnection http = NetworkUtil.prepareConnection(Data.profile.get(), "add");
+        HttpURLConnection http = NetworkUtil.prepareConnection(mProfile, "add");
         http.setRequestMethod("POST");
         http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
         http.setRequestProperty("Accept", "*/*");
@@ -116,27 +161,35 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
 
         UrlEncodedFormData params = new UrlEncodedFormData();
         params.addPair("_formid", "identify-add");
-        if (token != null) params.addPair("_token", token);
-        params.addPair("date", Globals.formatLedgerDate(ltr.getDate()));
-        params.addPair("description", ltr.getDescription());
-        for (LedgerTransactionAccount acc : ltr.getAccounts()) {
+        if (token != null)
+            params.addPair("_token", token);
+
+        SimpleDate transactionDate = transaction.getDateIfAny();
+        if (transactionDate == null)
+            transactionDate = SimpleDate.today();
+
+        params.addPair("date", Globals.formatLedgerDate(transactionDate));
+        params.addPair("description", transaction.getDescription());
+        for (LedgerTransactionAccount acc : transaction.getAccounts()) {
             params.addPair("account", acc.getAccountName());
             if (acc.isAmountSet())
                 params.addPair("amount", String.format(Locale.US, "%1.2f", acc.getAmount()));
-            else params.addPair("amount", "");
+            else
+                params.addPair("amount", "");
         }
 
         String body = params.toString();
         http.addRequestProperty("Content-Length", String.valueOf(body.length()));
 
-        Log.d("network", "request header: " + http.getRequestProperties().toString());
+        debug("network", "request header: " + http.getRequestProperties()
+                                                  .toString());
 
         try (OutputStream req = http.getOutputStream()) {
-            Log.d("network", "Request body: " + body);
+            debug("network", "Request body: " + body);
             req.write(body.getBytes(StandardCharsets.US_ASCII));
 
             try (InputStream resp = http.getInputStream()) {
-                Log.d("update_accounts", String.valueOf(http.getResponseCode()));
+                debug("update_accounts", String.valueOf(http.getResponseCode()));
                 if (http.getResponseCode() == 303) {
                     // everything is fine
                     return true;
@@ -153,10 +206,10 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
                             Matcher m = reSessionCookie.matcher(cookie);
                             if (m.matches()) {
                                 session = m.group(1);
-                                Log.d("network", "new session is " + session);
+                                debug("network", "new session is " + session);
                             }
                             else {
-                                Log.d("network", "set-cookie: " + cookie);
+                                debug("network", "set-cookie: " + cookie);
                                 Log.w("network",
                                         "Response Set-Cookie headers is not a _SESSION one");
                             }
@@ -171,12 +224,12 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
                             "<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
                     String line;
                     while ((line = reader.readLine()) != null) {
-                        //Log.d("dump", line);
+                        //debug("dump", line);
                         Matcher m = re.matcher(line);
                         if (m.matches()) {
                             token = m.group(1);
-                            Log.d("save-transaction", line);
-                            Log.d("save-transaction", "Token=" + token);
+                            debug("save-transaction", line);
+                            debug("save-transaction", "Token=" + token);
                             return false;       // retry
                         }
                     }
@@ -189,34 +242,66 @@ public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void
             }
         }
     }
-
     @Override
-    protected Void doInBackground(LedgerTransaction... ledgerTransactions) {
+    public void run() {
         error = null;
         try {
-            ltr = ledgerTransactions[0];
-
-            if (!sendOK()) {
-                int tried = 0;
-                while (!legacySendOK()) {
-                        tried++;
-                        if (tried >= 2)
-                            throw new IOException(String.format("aborting after %d tries", tried));
-                        sleep(100);
-                }
+            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);
+                        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();
+                    }
+                    break;
+                case html:
+                    legacySendOkWithRetry();
+                    break;
+                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));
     }
-
-    @Override
-    protected void onPostExecute(Void aVoid) {
-        super.onPostExecute(aVoid);
-        taskCallback.done(error);
+    private void legacySendOkWithRetry() throws IOException {
+        int tried = 0;
+        while (!legacySendOK()) {
+            tried++;
+            if (tried >= 2)
+                throw new IOException(String.format("aborting after %d tries", tried));
+            try {
+                sleep(100);
+            }
+            catch (InterruptedException e) {
+                e.printStackTrace();
+                break;
+            }
+        }
     }
-}
+}
\ No newline at end of file