package ru.mtusi.messenger; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; final class Input { private Input() {} static void fields(JsonNode body, String... allowed) { Set names = Set.of(allowed); if (body == null || !body.isObject() || body.size() != names.size()) { throw ApiException.invalid("Неверный набор полей JSON"); } body.fieldNames().forEachRemaining(name -> { if (!names.contains(name)) throw ApiException.invalid("Неизвестное поле JSON"); }); } static String text(JsonNode body, String field, int max) { JsonNode node = body.get(field); if (node == null || !node.isTextual()) throw ApiException.invalid("Поле должно быть строкой: " + field); String value = node.textValue(); if (value.codePointCount(0, value.length()) > max || value.codePoints().allMatch(Input::isUnicodeWhitespace)) { throw ApiException.invalid("Недопустимая длина или пустая строка: " + field); } return value; } static String password(JsonNode body) { JsonNode node = body.get("password"); if (node == null || !node.isTextual()) throw ApiException.invalid("Пароль должен быть строкой"); String value = node.textValue(); int length = value.codePointCount(0, value.length()); if (length < 12 || length > 128 || value.codePoints().allMatch(Input::isUnicodeWhitespace)) { throw ApiException.invalid("Пароль должен содержать от 12 до 128 непробельных символов"); } return value; } private static boolean isUnicodeWhitespace(int codePoint) { return codePoint == 0x0085 || Character.isWhitespace(codePoint) || Character.isSpaceChar(codePoint); } static UUID uuid(String value) { if (value == null || !value.matches("(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { throw ApiException.invalid("Некорректный UUID"); } return UUID.fromString(value); } static List members(JsonNode body) { JsonNode array = body.get("member_ids"); if (array == null || !array.isArray() || array.isEmpty() || array.size() > 100) { throw ApiException.invalid("member_ids должен содержать от 1 до 100 участников"); } List ids = new ArrayList<>(); for (JsonNode item : array) { if (!item.isTextual()) throw ApiException.invalid("Участник должен быть UUID-строкой"); ids.add(uuid(item.textValue())); } if (new HashSet<>(ids).size() != ids.size()) throw ApiException.invalid("Участники повторяются"); return ids; } static int limit(String value) { if (value == null) return 50; try { if (!value.matches("[0-9]{1,3}")) throw new NumberFormatException(); int limit = Integer.parseInt(value); if (limit < 1 || limit > 100) throw new NumberFormatException(); return limit; } catch (NumberFormatException exception) { throw ApiException.invalid("limit должен быть целым числом от 1 до 100"); } } }