From dfecd152c94ecfff73644b58a3c0b6bcead1f4ed Mon Sep 17 00:00:00 2001 From: "Luca Sorace \"Stranck" Date: Wed, 16 Oct 2024 19:38:40 +0200 Subject: [PATCH] Added pretix file upload --- .../backend/db/entities/pretix/Order.java | 8 +++- .../backend/service/pretix/PretixService.java | 45 +++++++++++-------- .../net/furizon/backend/utils/Download.java | 3 +- .../backend/utils/pretix/Constants.java | 1 + 4 files changed, 36 insertions(+), 21 deletions(-) diff --git a/src/main/java/net/furizon/backend/db/entities/pretix/Order.java b/src/main/java/net/furizon/backend/db/entities/pretix/Order.java index d4a452c..40466b0 100644 --- a/src/main/java/net/furizon/backend/db/entities/pretix/Order.java +++ b/src/main/java/net/furizon/backend/db/entities/pretix/Order.java @@ -7,6 +7,7 @@ import net.furizon.backend.db.entities.users.User; import net.furizon.backend.service.pretix.PretixService; import net.furizon.backend.utils.pretix.*; +import org.apache.http.entity.ContentType; import org.json.JSONArray; import org.json.JSONObject; @@ -14,6 +15,7 @@ import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.*; +import java.util.concurrent.TimeoutException; @Entity @Table(name = "orders") @@ -98,7 +100,7 @@ private void saveAnswers(PretixService ps) { case BOOLEAN -> ((boolean) o) ? "true" : "false"; case LIST_SINGLE_CHOICE -> (String) o; case LIST_MULTIPLE_CHOICE -> (String) o; - case FILE -> Constants.QUESTIONS_FILE_KEEP; + case FILE -> (String) o; case DATE -> o.toString(); case TIME -> o.toString(); case DATE_TIME -> o.toString(); @@ -117,6 +119,10 @@ public Object getAnswerValue(String answer, PretixService ps){ return answersData.get(answer); } + public void setAnswerFile(String answer, ContentType mimeType, String fileName, byte[] bytes, PretixService ps) throws TimeoutException { + String newAns = ps.uploadFile(mimeType, fileName, bytes); + this.setAnswerValue(answer, newAns, ps); + } public void setAnswerValue(String answer, Object value, PretixService ps){ if(answersData == null) loadAnswers(ps); answersData.put(answer, value); diff --git a/src/main/java/net/furizon/backend/service/pretix/PretixService.java b/src/main/java/net/furizon/backend/service/pretix/PretixService.java index e9d200e..356c80f 100644 --- a/src/main/java/net/furizon/backend/service/pretix/PretixService.java +++ b/src/main/java/net/furizon/backend/service/pretix/PretixService.java @@ -1,5 +1,6 @@ package net.furizon.backend.service.pretix; +import lombok.extern.slf4j.Slf4j; import net.furizon.backend.db.entities.pretix.Event; import net.furizon.backend.db.entities.pretix.Order; import net.furizon.backend.db.entities.users.User; @@ -11,6 +12,7 @@ import net.furizon.backend.utils.Download; import net.furizon.backend.utils.ThrowableSupplier; import net.furizon.backend.utils.configs.PretixConfig; +import org.apache.http.entity.ContentType; import org.apache.logging.log4j.util.TriConsumer; import org.json.JSONArray; import org.json.JSONException; @@ -18,8 +20,6 @@ import org.springframework.data.util.Pair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -35,6 +35,7 @@ * Describes all the iteractions via Pretix */ @Service +@Slf4j public class PretixService { private final IUserRepository userRepository; private final IEventRepository eventRepository; @@ -49,8 +50,6 @@ private PretixService (IUserRepository userRepository, IEventRepository eventRep this.pretixConfig = pretixConfig; } - private final static Logger LOGGER = LoggerFactory.getLogger(PretixService.class); - private PretixIdsMap pretixIdsCache = null; private class PretixIdsMap { @@ -174,7 +173,7 @@ private synchronized void reloadProducts(PretixIdsMap pretixIdsCache) throws Tim } public void fetchOrder(String code, String secret) throws TimeoutException { - Download.Response res = doGet("orders" + code.replaceAll("[^A-Za-z0-9]+", ""), pretixConfig.getEventUrl(), Constants.STATUS_CODES_WITH_404); + Download.Response res = doGet("orders" + code.replaceAll("[^A-Za-z0-9]+", ""), pretixConfig.getEventUrl(), Constants.STATUS_CODES_WITH_404, null); if(res.getStatusCode() == 404) throw new RuntimeException("Order not found"); JSONObject orderData = res.getResponseJson(); if(!orderData.getString("secret").equals(secret)) throw new RuntimeException("Order not found"); //Same exception to not leak matched order code @@ -303,6 +302,14 @@ public void reloadEvents() throws TimeoutException { } + public String uploadFile(ContentType mimeType, String fileName, byte[] data) throws TimeoutException { + Map headers = new HashMap<>(); + headers.put("Content-Type", mimeType.toString()); + headers.put("Content-Disposition", "attachment; filename=\"" + fileName + "\""); + return doPost("upload", data, pretixConfig.getBaseUrl(), Constants.STATUS_CODES_FILE_UPLOAD, headers).getResponseJson().getString("id"); + } + + public synchronized String translateQuestionId(int answerId){ return pretixIdsCache.questionIdentifiers.get(answerId); } @@ -319,7 +326,7 @@ public synchronized void submitAnswersToPretix(Order order) throws TimeoutExcept JSONArray ans = order.getOrderStatus() == OrderStatus.CANCELED ? new JSONArray() : new JSONArray(order.getAnswersRaw()); payload.put("answers", ans); - Download.Response res = doPatch("orderpositions/" + order.getAnswersMainPositionId(), payload, pretixConfig.getEventUrl(), null); + Download.Response res = doPatch("orderpositions/" + order.getAnswersMainPositionId(), payload, pretixConfig.getEventUrl(), null, null); if(res.getStatusCode() != 200){ try { @@ -327,8 +334,8 @@ public synchronized void submitAnswersToPretix(Order order) throws TimeoutExcept if (d.has("answers")) { JSONArray errs = d.getJSONArray("answers"); for(int i = 0; i < errs.length() && i < ans.length(); i++) - LOGGER.error("[ANSWERS SENDING] ERROR ON '" + ans.getString(0) + "': " + errs.getString(i)); - } else LOGGER.error("[ANSWERS SENDING] GENERIC ERROR. Response: " + res.toString()); + log.error("[ANSWERS SENDING] ERROR ON '" + ans.getString(0) + "': " + errs.getString(i)); + } else log.error("[ANSWERS SENDING] GENERIC ERROR. Response: " + res.toString()); } catch(JSONException e) { throw new RuntimeException("There has been an error while updating this answers."); } @@ -342,7 +349,7 @@ private void getAllPages(String url, String baseUrl, Consumer elemen while(true){ pages += 1; - Download.Response res = doGet(TextUtil.leadingSlash(url) + "?page=" + pages, baseUrl, Constants.STATUS_CODES_WITH_404); + Download.Response res = doGet(TextUtil.leadingSlash(url) + "?page=" + pages, baseUrl, Constants.STATUS_CODES_WITH_404, null); if(res.getStatusCode() == 404) break; JSONObject response = res.getResponseJson(); @@ -354,22 +361,22 @@ private void getAllPages(String url, String baseUrl, Consumer elemen } } - private static Download httpClient; + private Download httpClient; public void setupClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { httpClient = new Download(pretixConfig.getConnectionTimeout(), pretixConfig.getConnectionHeaders(), null, pretixConfig.getMaxConnections(), false); } - private Download.Response doGet(String url, String baseUrl, int[] expectedStatusCodes) throws TimeoutException { - return doRequest(url, () -> httpClient.get(TextUtil.leadingSlash(baseUrl) + url).go(), null, expectedStatusCodes, "GETing"); + private Download.Response doGet(String url, String baseUrl, int[] expectedStatusCodes, Map headers) throws TimeoutException { + return doRequest(url, () -> httpClient.get(TextUtil.leadingSlash(baseUrl) + url).addHeaders(headers).go(), null, expectedStatusCodes, "GETing"); } - private Download.Response doPost(String url, Object content, String baseUrl, int[] expectedStatusCodes) throws TimeoutException { - return doRequest(url, () -> httpClient.post(TextUtil.leadingSlash(baseUrl) + url).setBody(content).go(), null, expectedStatusCodes, "POSTing"); + private Download.Response doPost(String url, Object content, String baseUrl, int[] expectedStatusCodes, Map headers) throws TimeoutException { + return doRequest(url, () -> httpClient.post(TextUtil.leadingSlash(baseUrl) + url).addHeaders(headers).setBody(content).go(), null, expectedStatusCodes, "POSTing"); } - private Download.Response doPatch(String url, JSONObject json, String baseUrl, int[] expectedStatusCodes) throws TimeoutException { - return doRequest(url, () -> httpClient.patch(TextUtil.leadingSlash(baseUrl) + url).setJson(json).go(), null, expectedStatusCodes, "PATCHing"); + private Download.Response doPatch(String url, JSONObject json, String baseUrl, int[] expectedStatusCodes, Map headers) throws TimeoutException { + return doRequest(url, () -> httpClient.patch(TextUtil.leadingSlash(baseUrl) + url).addHeaders(headers).setJson(json).go(), null, expectedStatusCodes, "PATCHing"); } private Download.Response doRequest(String url, ThrowableSupplier doReq, Runnable metricsFunc, int[] expectedStatusCodes, String opLogStr) throws TimeoutException { @@ -385,19 +392,19 @@ private Download.Response doRequest(String url, ThrowableSupplier headers) { - this.headers.putAll(headers); + if(headers != null) + this.headers.putAll(headers); return this; } public Request setHeader(String name, String value) { diff --git a/src/main/java/net/furizon/backend/utils/pretix/Constants.java b/src/main/java/net/furizon/backend/utils/pretix/Constants.java index 60bf12b..82e3ddd 100644 --- a/src/main/java/net/furizon/backend/utils/pretix/Constants.java +++ b/src/main/java/net/furizon/backend/utils/pretix/Constants.java @@ -29,4 +29,5 @@ public class Constants { // Why? you have Spring Http Codes Class :) public static final int[] STATUS_CODES_WITH_404 = new int[] { 200, 404 }; public static final int[] STATUS_CODES_ONLY_200 = new int[] { 200 }; + public static final int[] STATUS_CODES_FILE_UPLOAD = new int[] { 201 }; }