1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package de.kaiserpfalzedv.commons.core.libravatar;
26
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.URI;
30 import java.nio.charset.Charset;
31 import java.util.Locale;
32
33 import org.apache.commons.codec.digest.DigestUtils;
34 import org.apache.commons.io.IOUtils;
35
36 import de.kaiserpfalzedv.commons.api.libravatar.Avatar;
37 import de.kaiserpfalzedv.commons.api.libravatar.AvatarException;
38 import de.kaiserpfalzedv.commons.api.libravatar.AvatarOptions;
39 import de.kaiserpfalzedv.commons.api.libravatar.LibravatarDefaultImage;
40 import jakarta.inject.Inject;
41 import lombok.EqualsAndHashCode;
42 import lombok.Getter;
43 import lombok.RequiredArgsConstructor;
44 import lombok.ToString;
45 import lombok.experimental.Accessors;
46 import lombok.extern.slf4j.Slf4j;
47
48 @RequiredArgsConstructor(onConstructor = @__(@Inject))
49 @ToString(onlyExplicitlyIncluded = true)
50 @EqualsAndHashCode(onlyExplicitlyIncluded = true)
51 @Accessors(chain = true, fluent = false)
52 @Slf4j
53 public class AvatarImpl implements Avatar {
54 @ToString.Include
55 @EqualsAndHashCode.Include
56 @Getter
57 private final String email;
58
59 @Override
60 public byte[] download(final de.kaiserpfalzedv.commons.api.libravatar.AvatarOptions options) {
61 try (InputStream is = URI.create(this.buildUrl(options)).toURL().openStream()) {
62 return IOUtils.toByteArray(is);
63 } catch (final IOException e) {
64 throw new AvatarException(e);
65 }
66 }
67
68 @Override
69 public String buildUrl(final AvatarOptions options) {
70 log.debug("avatar build. https={}, sha256={}, size={}",
71 options.useHttps(), options.useSHA256(), options.imageSize());
72
73 final StringBuilder sb = new StringBuilder(
74 options.useHttps() ? options.secureBaseUri()
75 : options.baseUri());
76
77 sb.append(
78 options.useSHA256() ? DigestUtils.sha256Hex(this.email.toLowerCase(Locale.getDefault()).getBytes(Charset.defaultCharset()))
79 : DigestUtils.md5Hex(this.email.toLowerCase(Locale.getDefault()).getBytes(Charset.defaultCharset())));
80
81 sb.append("?s=").append(options.imageSize());
82
83 sb.append(
84 options.defaultImage() != LibravatarDefaultImage.DEFAULT ? "&d=" + options.defaultImage().getCode()
85 : "");
86
87 return sb.toString();
88 }
89 }