Skip to content

Commit

Permalink
Added pretix file upload
Browse files Browse the repository at this point in the history
  • Loading branch information
stranck committed Oct 16, 2024
1 parent b3c6e82 commit dfecd15
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
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;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.TimeoutException;

@Entity
@Table(name = "orders")
Expand Down Expand Up @@ -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();
Expand All @@ -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);
Expand Down
45 changes: 26 additions & 19 deletions src/main/java/net/furizon/backend/service/pretix/PretixService.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -11,15 +12,14 @@
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;
import org.json.JSONObject;

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;

Expand All @@ -35,6 +35,7 @@
* Describes all the iteractions via Pretix
*/
@Service
@Slf4j
public class PretixService {
private final IUserRepository userRepository;
private final IEventRepository eventRepository;
Expand All @@ -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 {

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -303,6 +302,14 @@ public void reloadEvents() throws TimeoutException {
}


public String uploadFile(ContentType mimeType, String fileName, byte[] data) throws TimeoutException {
Map<String, String> 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);
}
Expand All @@ -319,16 +326,16 @@ 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 {
JSONObject d = res.getResponseJson();
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.");
}
Expand All @@ -342,7 +349,7 @@ private void getAllPages(String url, String baseUrl, Consumer<JSONObject> 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();
Expand All @@ -354,22 +361,22 @@ private void getAllPages(String url, String baseUrl, Consumer<JSONObject> 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<String, String> 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<String, String> 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<String, String> 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<Download.Response, Exception> doReq, Runnable metricsFunc, int[] expectedStatusCodes, String opLogStr) throws TimeoutException {
Expand All @@ -385,19 +392,19 @@ private Download.Response doRequest(String url, ThrowableSupplier<Download.Respo
int statusCode = r.getStatusCode();
if(allowedStates != null && !allowedStates.contains(statusCode)){
//incPretixErrors(); TODO
LOGGER.warn("[PRETIX] Got an unexpected status code ({}) while {} '{}'. Allowed status codes: {}", statusCode, opLogStr, url, allowedStates);
log.warn("[PRETIX] Got an unexpected status code ({}) while {} '{}'. Allowed status codes: {}", statusCode, opLogStr, url, allowedStates);
continue;
}
res = r;

} catch (Exception e) {
//incPretixErrors(); TODO
LOGGER.warn("[PRETIX] An error ({}) occurred while {} '{}':\n{}", i, opLogStr, url, e.getMessage());
log.warn("[PRETIX] An error ({}) occurred while {} '{}':\n{}", i, opLogStr, url, e.getMessage());
}
if (res != null) break;
}
if(res == null){
LOGGER.error("[PRETIX] Reached PRETIX_REQUESTS_MAX ({}) while {} '{}'. Aborting", maxRetries, opLogStr, url);
log.error("[PRETIX] Reached PRETIX_REQUESTS_MAX ({}) while {} '{}'. Aborting", maxRetries, opLogStr, url);
throw new TimeoutException("PRETIX_REQUESTS_MAX reached while " + opLogStr + " to pretix.");
}
return res;
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/net/furizon/backend/utils/Download.java
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,8 @@ public Request(String url) {
this.url = url;
}
public Request addHeaders(Map<String, String> headers) {
this.headers.putAll(headers);
if(headers != null)
this.headers.putAll(headers);
return this;
}
public Request setHeader(String name, String value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}

0 comments on commit dfecd15

Please sign in to comment.