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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use futures_util::FutureExt;
use reqwest::Client;
use crate::{
errors::{ChorusError, ChorusResult},
instance::ChorusUser,
ratelimiter::ChorusRequest,
types::{
AuthorizeConnectionReturn, AuthorizeConnectionSchema, Connection, ConnectionSubreddit,
ConnectionType, CreateConnectionCallbackSchema, CreateContactSyncConnectionSchema,
CreateDomainConnectionError, CreateDomainConnectionReturn, GetConnectionAccessTokenReturn,
LimitType, ModifyConnectionSchema,
},
};
impl ChorusUser {
/// Fetches a url that can be used for authorizing a new connection.
///
/// The user should then visit the url and authenticate to create the connection.
///
/// # Notes
/// This route seems to be preferred by the official infrastructure (client) to
/// [Self::create_connection_callback].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#authorize-user-connection>
///
/// Note: it doesn't seem to be actually unauthenticated
pub async fn authorize_connection(
&mut self,
connection_type: ConnectionType,
query_parameters: AuthorizeConnectionSchema,
) -> ChorusResult<String> {
let connection_type_string = serde_json::to_string(&connection_type)
.expect("Failed to serialize connection type!")
.replace('"', "");
let request = Client::new()
.get(format!(
"{}/connections/{}/authorize",
self.belongs_to.read().unwrap().urls.api,
connection_type_string
))
.query(&query_parameters);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
// Note: ommiting authorization causes a 401 Unauthorized,
// even though discord.food mentions it as unauthenticated
chorus_request
.send_and_deserialize_response::<AuthorizeConnectionReturn>(self)
.await
.map(|response| response.url)
}
/// Creates a new connection for the current user.
///
/// # Notes
/// The official infrastructure (client) prefers the route
/// [Self::authorize_connection] to this one.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#create-user-connection-callback>
// TODO: When is this called? When should it be used over authorize_connection?
pub async fn create_connection_callback(
&mut self,
connection_type: ConnectionType,
json_schema: CreateConnectionCallbackSchema,
) -> ChorusResult<Connection> {
let connection_type_string = serde_json::to_string(&connection_type)
.expect("Failed to serialize connection type!")
.replace('"', "");
let request = Client::new()
.post(format!(
"{}/connections/{}/callback",
self.belongs_to.read().unwrap().urls.api,
connection_type_string
))
.json(&json_schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_deserialize_response(self).await
}
/// Creates a new contact sync connection for the current user.
///
/// # Notes
/// To create normal connection types, see [Self::authorize_connection] and
/// [Self::create_connection_callback]
///
/// # Reference
/// See <https://docs.discord.food/resources/user#create-contact-sync-connection>
pub async fn create_contact_sync_connection(
&mut self,
connection_account_id: &String,
json_schema: CreateContactSyncConnectionSchema,
) -> ChorusResult<Connection> {
let request = Client::new()
.put(format!(
"{}/users/@me/connections/contacts/{}",
self.belongs_to.read().unwrap().urls.api,
connection_account_id
))
.json(&json_schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_deserialize_response(self).await
}
/// Creates a new domain connection for the current user.
///
/// This route has two possible successful return values:
/// [CreateDomainConnectionReturn::Ok] and [CreateDomainConnectionReturn::ProofNeeded]
///
/// To properly handle both, please see their respective documentation pages.
///
/// # Notes
/// To create normal connection types, see [Self::authorize_connection] and
/// [Self::create_connection_callback]
///
/// As of 2024/08/21, Spacebar does not yet implement this endpoint.
///
/// # Examples
/// ```no_run
/// # tokio_test::block_on(async {
/// # use chorus::{instance::ChorusUser, types::CreateDomainConnectionReturn};
/// # mod tests::common;
/// # let mut bundle = tests::common::setup().await;
/// let domain = "example.com".to_string();
///
/// let user: ChorusUser; // Get this by registering / logging in
/// # let user = bundle.user;
///
/// let result = user.create_domain_connection(&domain).await;
///
/// if let Ok(returned) = result {
/// match returned {
/// CreateDomainConnectionReturn::ProofNeeded(proof) => {
/// println!("Additional proof needed!");
/// println!("Either:");
/// println!("");
/// println!("- create a DNS TXT record with the name _discord.{domain} and content {proof}");
/// println!("or");
/// println!("- create a file at https://{domain}/.well-known/discord with the content {proof}");
/// // Once the user has added the proof, retry calling the endpoint
/// }
/// CreateDomainConnectionReturn::Ok(connection) => {
/// println!("Successfulyl created connection! {:?}", connection);
/// }
/// }
/// } else {
/// println!("Failed to create connection: {:?}", result);
/// }
/// # tests::common::teardown(bundle).await;
/// # })
/// ```
///
/// # Reference
/// See <https://docs.discord.food/resources/user#create-domain-connection>
pub async fn create_domain_connection(
&mut self,
domain: &String,
) -> ChorusResult<CreateDomainConnectionReturn> {
let request = Client::new().post(format!(
"{}/users/@me/connections/domain/{}",
self.belongs_to.read().unwrap().urls.api,
domain
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
let result = chorus_request.send(self).await;
match result {
Ok(response) => {
let connection: Connection = ChorusRequest::deserialize_response(response).await?;
Ok(CreateDomainConnectionReturn::Ok(connection))
}
Err(e) => {
match e {
ChorusError::ReceivedError {
ref error,
ref response_text,
} => {
// TODO: maybe there is a JSON code for this?
if error.http_status.as_u16() == 400 {
let try_deserialize: Result<
CreateDomainConnectionError,
serde_json::Error,
> = serde_json::from_str(response_text);
if let Ok(deserialized) = try_deserialize {
return Ok(CreateDomainConnectionReturn::ProofNeeded(
deserialized.proof,
));
}
}
Err(e)
}
_ => Err(e),
}
}
}
}
/// Fetches the current user's [Connection]s
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-connections>
pub async fn get_connections(&mut self) -> ChorusResult<Vec<Connection>> {
let request = Client::new().get(format!(
"{}/users/@me/connections",
self.belongs_to.read().unwrap().urls.api,
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_deserialize_response(self).await
}
/// Refreshes a local user's [Connection].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#refresh-user-connection>
pub async fn refresh_connection(
&mut self,
connection_type: ConnectionType,
connection_account_id: &String,
) -> ChorusResult<()> {
let connection_type_string = serde_json::to_string(&connection_type)
.expect("Failed to serialize connection type!")
.replace('"', "");
let request = Client::new().post(format!(
"{}/users/@me/connections/{}/{}/refresh",
self.belongs_to.read().unwrap().urls.api,
connection_type_string,
connection_account_id
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_handle_as_result(self).await
}
/// Changes settings on a local user's [Connection].
///
/// # Notes
/// Not all connection types support all parameters.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-user-connection>
pub async fn modify_connection(
&mut self,
connection_type: ConnectionType,
connection_account_id: &String,
json_schema: ModifyConnectionSchema,
) -> ChorusResult<Connection> {
let connection_type_string = serde_json::to_string(&connection_type)
.expect("Failed to serialize connection type!")
.replace('"', "");
let request = Client::new()
.patch(format!(
"{}/users/@me/connections/{}/{}",
self.belongs_to.read().unwrap().urls.api,
connection_type_string,
connection_account_id
))
.json(&json_schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_deserialize_response(self).await
}
/// Deletes a local user's [Connection].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#delete-user-connection>
pub async fn delete_connection(
&mut self,
connection_type: ConnectionType,
connection_account_id: &String,
) -> ChorusResult<()> {
let connection_type_string = serde_json::to_string(&connection_type)
.expect("Failed to serialize connection type!")
.replace('"', "");
let request = Client::new().delete(format!(
"{}/users/@me/connections/{}/{}",
self.belongs_to.read().unwrap().urls.api,
connection_type_string,
connection_account_id
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_handle_as_result(self).await
}
/// Returns a new access token for the given connection.
///
/// Only available for [ConnectionType::Twitch], [ConnectionType::YouTube] and [ConnectionType::Spotify] connections.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-connection-access-token>
pub async fn get_connection_access_token(
&mut self,
connection_type: ConnectionType,
connection_account_id: &String,
) -> ChorusResult<String> {
let connection_type_string = serde_json::to_string(&connection_type)
.expect("Failed to serialize connection type!")
.replace('"', "");
let request = Client::new().get(format!(
"{}/users/@me/connections/{}/{}/access-token",
self.belongs_to.read().unwrap().urls.api,
connection_type_string,
connection_account_id
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request
.send_and_deserialize_response::<GetConnectionAccessTokenReturn>(self)
.await
.map(|res| res.access_token)
}
/// Fetches a list of [subreddits](crate::types::ConnectionSubreddit)
/// the connected account moderates.
///
/// Only available for [ConnectionType::Reddit] connections.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-connection-subreddits>
pub async fn get_connection_subreddits(
&mut self,
connection_account_id: &String,
) -> ChorusResult<Vec<ConnectionSubreddit>> {
let request = Client::new().get(format!(
"{}/users/@me/connections/reddit/{}/subreddits",
self.belongs_to.read().unwrap().urls.api,
connection_account_id
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_deserialize_response(self).await
}
}