-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathPatreonAPI.java
More file actions
236 lines (214 loc) · 8.54 KB
/
PatreonAPI.java
File metadata and controls
236 lines (214 loc) · 8.54 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package com.patreon;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.github.jasminb.jsonapi.*;
import com.patreon.resources.Campaign;
import com.patreon.resources.Pledge;
import com.patreon.resources.RequestUtil;
import com.patreon.resources.User;
import com.patreon.resources.shared.BaseResource;
import com.patreon.resources.shared.Field;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
public class PatreonAPI {
/**
* The base URI for requests to the patreon API. This may be overridden (e.g. for testing) by passing
* -Dpatreon.rest.uri="https://my.other.server.com" as jvm arguments
*/
public static final String BASE_URI = System.getProperty("patreon.rest.uri", "https://www.patreon.com");
private static final Logger LOG = LoggerFactory.getLogger(PatreonAPI.class);
private final String accessToken;
private final RequestUtil requestUtil;
private ResourceConverter converter;
private final Proxy proxy;
/**
* Create a new instance of the Patreon API. You only need <b>one</b> of these objects unless you are using the API
* with multiple tokens
*
* @param accessToken The "Creator's Access Token" found on
* <a href="https://www.patreon.com/platform/documentation/clients">the patreon client page</a>
* <b>OR</b> OAuth access token
*/
public PatreonAPI(String accessToken) {
this(accessToken, new RequestUtil());
}
public PatreonAPI(String accessToken, Proxy proxy) {
this(accessToken, new RequestUtil(), proxy);
}
/**
* For use in test.
*/
PatreonAPI(String accessToken, RequestUtil requestUtil) {
this(accessToken, requestUtil, null);
}
/**
* For use in test.
*/
PatreonAPI(String accessToken, RequestUtil requestUtil, Proxy proxy) {
this.accessToken = accessToken;
this.requestUtil = requestUtil;
this.proxy = proxy;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.converter = new ResourceConverter(
objectMapper,
User.class,
Campaign.class,
Pledge.class
);
this.converter.enableDeserializationOption(DeserializationFeature.ALLOW_UNKNOWN_INCLUSIONS);
}
/**
* Get the user object of the creator
*
* @return the current user
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<User> fetchUser() throws IOException {
return fetchUser(null);
}
/**
* Get the user object of the creator
*
* @param optionalFields A list of optional fields to request, or null. See {@link User.UserField}
* @return the current user
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<User> fetchUser(Collection<User.UserField> optionalFields) throws IOException {
URIBuilder pathBuilder = new URIBuilder()
.setPath("current_user")
.addParameter("include", "pledges");
if (optionalFields != null) {
Set<User.UserField> optionalAndDefaultFields = new HashSet<>(optionalFields);
optionalAndDefaultFields.addAll(User.UserField.getDefaultFields());
addFieldsParam(pathBuilder, User.class, optionalAndDefaultFields);
}
return converter.readDocument(
getDataStream(pathBuilder.toString()),
User.class
);
}
/**
* Get a list of campaigns the current creator is running - also contains other related data like Goals
* Note: The first campaign data object is located at index 0 in the data list
*
* @return the list of campaigns
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<List<Campaign>> fetchCampaigns() throws IOException {
String path = new URIBuilder()
.setPath("current_user/campaigns")
.addParameter("include", "rewards,creator,goals")
.toString();
return converter.readDocumentCollection(
getDataStream(path),
Campaign.class
);
}
/**
* Retrieve pledges for the specified campaign
*
* @param campaignId id for campaign to retrieve
* @param pageSize how many pledges to return
* @param pageCursor A cursor retreived from a previous API call, or null for the initial page.
* See {@link #getNextCursorFromDocument(JSONAPIDocument)}
* @return the page of pledges
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<List<Pledge>> fetchPageOfPledges(String campaignId, int pageSize, String pageCursor) throws IOException {
return fetchPageOfPledges(campaignId, pageSize, pageCursor, null);
}
/**
* Retrieve pledges for the specified campaign
*
* @param campaignId id for campaign to retrieve
* @param pageSize how many pledges to return
* @param pageCursor A cursor retreived from a previous API call, or null for the initial page.
* See {@link #getNextCursorFromDocument(JSONAPIDocument)}
* @param optionalFields A list of optional fields to return. See {@link Pledge.PledgeField}
* @return the page of pledges
* @throws IOException Thrown when the GET request failed
*/
public JSONAPIDocument<List<Pledge>> fetchPageOfPledges(String campaignId, int pageSize, String pageCursor, Collection<Pledge.PledgeField> optionalFields) throws IOException {
URIBuilder pathBuilder = new URIBuilder()
.setPath(String.format("campaigns/%s/pledges", campaignId))
.addParameter("page[count]", String.valueOf(pageSize));
if (pageCursor != null) {
pathBuilder.addParameter("page[cursor]", pageCursor);
}
if (optionalFields != null) {
Set<Pledge.PledgeField> optionalAndDefaultFields = new HashSet<>(optionalFields);
optionalAndDefaultFields.addAll(Pledge.PledgeField.getDefaultFields());
addFieldsParam(pathBuilder, Pledge.class, optionalAndDefaultFields);
}
return converter.readDocumentCollection(
getDataStream(pathBuilder.toString()),
Pledge.class
);
}
public String getNextCursorFromDocument(JSONAPIDocument document) {
Links links = document.getLinks();
if (links == null) {
return null;
}
Link nextLink = links.getNext();
if (nextLink == null) {
return null;
}
String nextLinkString = nextLink.toString();
try {
List<NameValuePair> queryParameters = URLEncodedUtils.parse(new URI(nextLinkString), "utf8");
for (NameValuePair pair : queryParameters) {
String name = pair.getName();
if (name.equals("page[cursor]")) {
return pair.getValue();
}
}
} catch (URISyntaxException e) {
LOG.error(e.getMessage());
}
return null;
}
public List<Pledge> fetchAllPledges(String campaignId) throws IOException {
Set<Pledge> pledges = new HashSet<>();
String cursor = null;
while (true) {
JSONAPIDocument<List<Pledge>> pledgesPage = fetchPageOfPledges(campaignId, 15, cursor);
pledges.addAll(pledgesPage.get());
cursor = getNextCursorFromDocument(pledgesPage);
if (cursor == null) {
break;
}
}
return new ArrayList<>(pledges);
}
private InputStream getDataStream(String suffix) throws IOException {
return this.requestUtil.request(suffix, this.accessToken, this.proxy);
}
/**
* Add fields[type]=fieldName,fieldName,fieldName as a query parameter to the request represented by builder
* @param builder A URIBuilder building a request to the API
* @param type A BaseResource annotated with {@link com.github.jasminb.jsonapi.annotations.Type}
* @param fields A list of fields to include. Only fields in this list will be retrieved in the query
* @return builder
*/
private URIBuilder addFieldsParam(URIBuilder builder, Class<? extends BaseResource> type, Collection<? extends Field> fields) {
List<String> fieldNames = new ArrayList<>();
for (Field f : fields) {
fieldNames.add(f.getPropertyName());
}
String typeStr = BaseResource.getType(type);
builder.addParameter("fields[" + typeStr + "]", String.join(",", fieldNames));
return builder;
}
}