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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
// 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 std::{
collections::HashMap,
sync::{Arc, RwLock},
};
use reqwest::Client;
use serde_json::to_string;
use crate::{
errors::{ChorusError, ChorusResult},
instance::{ChorusUser, Instance},
ratelimiter::ChorusRequest,
types::{
AuthorizeConnectionSchema, BurstCreditsInfo, ConnectionType, CreateUserHarvestSchema,
DeleteDisableUserSchema, GetPomeloEligibilityReturn, GetPomeloSuggestionsReturn,
GetRecentMentionsSchema, GetUserProfileSchema, GuildAffinities, Harvest,
HarvestBackendType, LimitType, ModifyUserNoteSchema, PremiumUsage, PublicUser, Snowflake,
User, UserAffinities, UserModifyProfileSchema, UserModifySchema, UserNote, UserProfile,
UserProfileMetadata, UserSettings, VerifyUserEmailChangeResponse,
VerifyUserEmailChangeSchema,
},
};
impl ChorusUser {
/// Gets the local / current user.
///
/// # Notes
/// This function is a wrapper around [`User::get_current`].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-current-user>
pub async fn get_current_user(&mut self) -> ChorusResult<User> {
User::get_current(self).await
}
/// Gets a non-local user by their id
///
/// # Notes
/// This function is a wrapper around [`User::get`].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user>
pub async fn get_user(&mut self, id: Snowflake) -> ChorusResult<PublicUser> {
User::get(self, id).await
}
/// Gets a non-local user by their unique username.
///
/// As of 2024/07/28, Spacebar does not yet implement this endpoint.
///
/// If fetching with a pomelo username, discriminator should be set to None.
///
/// This route also permits fetching users with their old pre-pomelo username#discriminator
/// combo.
///
/// Note:
///
/// "Unless the target user is a bot, you must be able to add
/// the user as a friend to resolve them by username.
///
/// Due to this restriction, you are not able to resolve your own username."
///
/// # Notes
/// This function is a wrapper around [`User::get_by_username`].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-by-username>
pub async fn get_user_by_username(
&mut self,
username: &String,
discriminator: Option<&String>,
) -> ChorusResult<PublicUser> {
User::get_by_username(self, username, discriminator).await
}
/// Gets the user's settings.
///
/// # Notes
/// This function is a wrapper around [`User::get_settings`].
pub async fn get_settings(&mut self) -> ChorusResult<UserSettings> {
User::get_settings(self).await
}
/// Modifies the current user's representation. (See [`User`])
///
/// # Notes
/// This route requires MFA.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-current-user>
pub async fn modify(&mut self, modify_schema: UserModifySchema) -> ChorusResult<User> {
// See <https://docs.discord.food/resources/user#json-params>, note 1
let requires_current_password = modify_schema.username.is_some()
|| modify_schema.discriminator.is_some()
|| modify_schema.email.is_some()
|| modify_schema.date_of_birth.is_some()
|| modify_schema.new_password.is_some();
if requires_current_password && modify_schema.current_password.is_none() {
return Err(ChorusError::PasswordRequired);
}
let request = Client::new()
.patch(format!(
"{}/users/@me",
self.belongs_to.read().unwrap().urls.api
))
.json(&modify_schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_maybe_mfa(&self.mfa_token)
.with_headers_for(self);
chorus_request
.send_and_deserialize_response::<User>(self)
.await
}
/// Disables the current user's account.
///
/// Invalidates all active tokens.
///
/// Requires the user's current password (if any)
///
/// # Notes
/// This route requires MFA.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#disable-user>
pub async fn disable(&mut self, schema: DeleteDisableUserSchema) -> ChorusResult<()> {
let request = Client::new()
.post(format!(
"{}/users/@me/disable",
self.belongs_to.read().unwrap().urls.api
))
.json(&schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_maybe_mfa(&self.mfa_token)
.with_headers_for(self);
chorus_request.send_and_handle_as_result(self).await
}
/// Deletes the current user from the Instance.
///
/// Requires the user's current password (if any)
///
/// # Notes
/// This route requires MFA.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#delete-user>
pub async fn delete(&mut self, schema: DeleteDisableUserSchema) -> ChorusResult<()> {
let request = Client::new()
.post(format!(
"{}/users/@me/delete",
self.belongs_to.read().unwrap().urls.api
))
.json(&schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_maybe_mfa(&self.mfa_token)
.with_headers_for(self);
chorus_request.send_and_handle_as_result(self).await
}
/// Gets a user's profile object by their id.
///
/// This endpoint requires one of the following:
///
/// - The other user is a bot
/// - The other user shares a mutual guild with the current user
/// - The other user is a friend of the current user
/// - The other user is a friend suggestion of the current user
/// - The other user has an outgoing friend request to the current user
///
/// # Notes
/// This function is a wrapper around [`User::get_profile`].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-profile>
pub async fn get_user_profile(
&mut self,
id: Snowflake,
query_parameters: GetUserProfileSchema,
) -> ChorusResult<UserProfile> {
User::get_profile(self, id, query_parameters).await
}
/// Modifies the current user's profile.
///
/// Returns the updated [UserProfileMetadata].
///
/// # Notes
/// This function is a wrapper around [`User::modify_profile`].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-user-profile>
pub async fn modify_profile(
&mut self,
schema: UserModifyProfileSchema,
) -> ChorusResult<UserProfileMetadata> {
User::modify_profile(self, schema).await
}
/// Initiates the email change process.
///
/// Sends a verification code to the current user's email.
///
/// Should be followed up with [Self::verify_email_change]
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-user-email>
pub async fn initiate_email_change(&mut self) -> ChorusResult<()> {
let request = Client::new().put(format!(
"{}/users/@me/email",
self.belongs_to.read().unwrap().urls.api
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_handle_as_result(self).await
}
/// Verifies a code sent to change the current user's email.
///
/// This endpoint returns a token which can be used with [Self::modify]
/// to set a new email address (email_token).
///
/// # Notes
/// Should be the follow-up to [Self::initiate_email_change]
///
/// As of 2024/08/08, Spacebar does not yet implement this endpoint.
// FIXME: Does this mean PUT users/@me/email is different?
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-user-email>
pub async fn verify_email_change(
&mut self,
schema: VerifyUserEmailChangeSchema,
) -> ChorusResult<VerifyUserEmailChangeResponse> {
let request = Client::new()
.post(format!(
"{}/users/@me/email/verify-code",
self.belongs_to.read().unwrap().urls.api
))
.json(&schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request
.send_and_deserialize_response::<VerifyUserEmailChangeResponse>(self)
.await
}
/// Returns a suggested unique username based on the current user's username.
///
/// # Notes:
/// "This endpoint is used during the pomelo migration flow.
///
/// The user must be in the rollout to use this endpoint."
///
/// If a user has already migrated, this endpoint will likely return a 401 Unauthorized
/// ([ChorusError::NoPermission])
///
/// As of 2024/08/08, Spacebar does not yet implement this endpoint.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-pomelo-suggestions>
pub async fn get_pomelo_suggestions(&mut self) -> ChorusResult<String> {
let request = Client::new().get(format!(
"{}/users/@me/pomelo-suggestions",
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::<GetPomeloSuggestionsReturn>(self)
.await
.map(|returned| returned.username)
}
/// Checks whether a unique username is available.
///
/// Returns whether the username is not taken yet.
///
/// # Notes
/// As of 2024/08/08, Spacebar does not yet implement this endpoint.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-pomelo-eligibility>
pub async fn get_pomelo_eligibility(&mut self, username: &String) -> ChorusResult<bool> {
let request = Client::new()
.post(format!(
"{}/users/@me/pomelo-attempt",
self.belongs_to.read().unwrap().urls.api
))
// FIXME: should we create a type for this?
.body(format!(r#"{{ "username": {:?} }}"#, username))
.header("Content-Type", "application/json");
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request
.send_and_deserialize_response::<GetPomeloEligibilityReturn>(self)
.await
.map(|returned| !returned.taken)
}
/// Migrates the user from the username#discriminator to the unique username system.
///
/// Fires a [UserUpdate](crate::types::UserUpdate) gateway event.
///
/// Updates [Self::object] to an updated representation returned by the server.
// FIXME: Is this appropriate behaviour?
///
/// # Notes
/// "This endpoint is used during the pomelo migration flow.
///
/// The user must be in the rollout to use this endpoint."
///
/// If a user has already migrated, this endpoint will likely return a 401 Unauthorized
/// ([ChorusError::NoPermission])
//
/// As of 2024/08/08, Spacebar does not yet implement this endpoint.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#create-pomelo-migration>
pub async fn create_pomelo_migration(&mut self, username: &String) -> ChorusResult<()> {
let request = Client::new()
.post(format!(
"{}/users/@me/pomelo",
self.belongs_to.read().unwrap().urls.api
))
// FIXME: should we create a type for this?
.body(format!(r#"{{ "username": {:?} }}"#, username))
.header("Content-Type", "application/json");
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
let result = chorus_request
.send_and_deserialize_response::<User>(self)
.await;
// FIXME: Does UserUpdate do this automatically? or would a user need to manually observe ChorusUser::object
if let Ok(new_object) = result {
*self.object.write().unwrap() = new_object;
return ChorusResult::Ok(());
}
ChorusResult::Err(result.err().unwrap())
}
/// Fetches a list of [Message](crate::types::Message)s that the current user has been
/// mentioned in during the last 7 days.
///
/// # Notes
/// As of 2024/08/09, Spacebar does not yet implement this endpoint.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-recent-mentions>
pub async fn get_recent_mentions(
&mut self,
query_parameters: GetRecentMentionsSchema,
) -> ChorusResult<Vec<crate::types::Message>> {
let request = Client::new()
.get(format!(
"{}/users/@me/mentions",
self.belongs_to.read().unwrap().urls.api
))
.query(&query_parameters);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request
.send_and_deserialize_response::<Vec<crate::types::Message>>(self)
.await
}
/// Acknowledges a message the current user has been mentioned in.
///
/// Fires a `RecentMentionDelete` gateway event. (Note: yet to be implemented in chorus, see [#545](https://github.com/polyphony-chat/chorus/issues/545))
///
/// # Notes
/// As of 2024/08/09, Spacebar does not yet implement this endpoint.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#delete-recent-mention>
pub async fn delete_recent_mention(&mut self, message_id: Snowflake) -> ChorusResult<()> {
let request = Client::new().delete(format!(
"{}/users/@me/mentions/{}",
self.belongs_to.read().unwrap().urls.api,
message_id
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_handle_as_result(self).await
}
/// If it exists, returns the most recent [Harvest] (personal data harvest request).
///
/// To create a new [Harvest], see [Self::create_harvest].
///
/// # Notes
/// As of 2024/08/09, Spacebar does not yet implement this endpoint. (Or data harvesting)
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-harvest>
pub async fn get_harvest(&mut self) -> ChorusResult<Option<Harvest>> {
let request = Client::new().get(format!(
"{}/users/@me/harvest",
self.belongs_to.read().unwrap().urls.api,
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
// Manual handling, because a 204 with no harvest is a success state,
// but we also need to deserialize stuff if it's a 200
// TODO: Maybe make this a method on ChorusRequest if we need it a lot.
let response = chorus_request.send(self).await?;
log::trace!("Got response: {:?}", response);
let http_status = response.status();
if response.status() == http::StatusCode::NO_CONTENT {
return Ok(None);
}
let response_text = match response.text().await {
Ok(string) => string,
Err(e) => {
return Err(ChorusError::InvalidResponse {
error: format!(
"Error while trying to process the HTTP response into a String: {}",
e
),
http_status,
});
}
};
let object = match serde_json::from_str::<Harvest>(&response_text) {
Ok(object) => object,
Err(e) => {
return Err(ChorusError::InvalidResponse {
error: format!(
"Error while trying to deserialize the JSON response into requested type T: {}. JSON Response: {}",
e, response_text
),
http_status
})
}
};
Ok(Some(object))
}
/// Creates a personal data harvest request ([Harvest]) for the current user.
///
/// # Notes
/// To fetch the latest existing harvest, see [Self::get_harvest].
///
/// Invalid options in the backends array are ignored.
///
/// If the array is empty (after ignoring), it requests all [HarvestBackendType]s.
///
/// As of 2024/08/09, Spacebar does not yet implement this endpoint. (Or data harvesting)
///
/// # Reference
/// See <https://docs.discord.food/resources/user#create-user-harvest>
pub async fn create_harvest(
&mut self,
backends: Vec<HarvestBackendType>,
) -> ChorusResult<Harvest> {
let schema = if backends.is_empty() {
CreateUserHarvestSchema { backends: None }
} else {
CreateUserHarvestSchema {
backends: Some(backends),
}
};
let request = Client::new()
.post(format!(
"{}/users/@me/harvest",
self.belongs_to.read().unwrap().urls.api,
))
.json(&schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(self);
chorus_request.send_and_deserialize_response(self).await
}
/// Returns a mapping of user IDs ([Snowflake]s) to notes ([String]s) for the current user.
///
/// # Notes
/// As of 2024/08/21, Spacebar does not yet implement this endpoint.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-notes>
pub async fn get_user_notes(&mut self) -> ChorusResult<HashMap<Snowflake, String>> {
let request = Client::new().get(format!(
"{}/users/@me/notes",
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
}
/// Fetches the note ([UserNote]) for the given user.
///
/// If the current user has no note for the target, this endpoint
/// returns `Err(NotFound { error: "{\"message\": \"Unknown User\", \"code\": 10013}" })`
///
/// # Notes
/// This function is a wrapper around [`User::get_note`].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-note>
pub async fn get_user_note(&mut self, target_user_id: Snowflake) -> ChorusResult<UserNote> {
User::get_note(self, target_user_id).await
}
/// Sets the note for the given user.
///
/// Fires a `UserNoteUpdate` gateway event. (Note: yet to be implemented in chorus, see [#546](https://github.com/polyphony-chat/chorus/issues/546))
///
/// # Notes
/// This function is a wrapper around [`User::set_note`].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-user-note>
pub async fn set_user_note(
&mut self,
target_user_id: Snowflake,
note: Option<String>,
) -> ChorusResult<()> {
User::set_note(self, target_user_id, note).await
}
/// Fetches the current user's affinity scores for other users.
///
/// (Affinity scores are a measure of how likely a user is to be friends with another user.)
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-affinities>
pub async fn get_user_affinities(&mut self) -> ChorusResult<UserAffinities> {
let request = Client::new().get(format!(
"{}/users/@me/affinities/users",
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
}
/// Fetches the current user's affinity scores for their joined guilds.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-guild-affinities>
pub async fn get_guild_affinities(&mut self) -> ChorusResult<GuildAffinities> {
let request = Client::new().get(format!(
"{}/users/@me/affinities/guilds",
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
}
/// Fetches the current user's usage of various premium perks ([PremiumUsage] object).
///
/// The local user must have premium (nitro), otherwise the request will fail
/// with a 404 NotFound error and the message {"message": "Premium usage not available", "code": 10084}.
///
/// # Notes
/// As of 2024/08/16, Spacebar does not yet implement this endpoint.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-premium-usage>
pub async fn get_premium_usage(&mut self) -> ChorusResult<PremiumUsage> {
let request = Client::new().get(format!(
"{}/users/@me/premium-usage",
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
}
/// Fetches info about the current user's burst credits
/// (how many are remaining, when they will replenish).
///
/// Burst credits are used to create burst reactions.
///
/// # Notes
/// As of 2024/08/18, Spacebar does not yet implement this endpoint.
pub async fn get_burst_credits(&mut self) -> ChorusResult<BurstCreditsInfo> {
let request = Client::new().get(format!(
"{}/users/@me/burst-credits",
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
}
}
impl User {
/// Gets the local / current user.
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-current-user>
pub async fn get_current(user: &mut ChorusUser) -> ChorusResult<User> {
let url_api = user.belongs_to.read().unwrap().urls.api.clone();
let url = format!("{}/users/@me", url_api);
let request = reqwest::Client::new().get(url);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::Global,
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<User>(user)
.await
}
/// Gets a non-local user by their id
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user>
pub async fn get(user: &mut ChorusUser, id: Snowflake) -> ChorusResult<PublicUser> {
let url_api = user.belongs_to.read().unwrap().urls.api.clone();
let url = format!("{}/users/{}", url_api, id);
let request = reqwest::Client::new().get(url);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::Global,
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<PublicUser>(user)
.await
}
/// Gets a user by their unique username.
///
/// As of 2024/07/28, Spacebar does not yet implement this endpoint.
///
/// If fetching with a pomelo username, discriminator should be set to None.
///
/// This route also permits fetching users with their old pre-pomelo username#discriminator
/// combo.
///
/// Note:
///
/// "Unless the target user is a bot, you must be able to add
/// the user as a friend to resolve them by username.
///
/// Due to this restriction, you are not able to resolve your own username."
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-by-username>
pub async fn get_by_username(
user: &mut ChorusUser,
username: &String,
discriminator: Option<&String>,
) -> ChorusResult<PublicUser> {
let url_api = user.belongs_to.read().unwrap().urls.api.clone();
let url = format!("{}/users/username/{username}", url_api);
let mut request = reqwest::Client::new().get(url);
if let Some(some_discriminator) = discriminator {
request = request.query(&[("discriminator", some_discriminator)]);
}
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::Global,
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<PublicUser>(user)
.await
}
/// Gets the current user's settings.
///
/// # Reference
/// See <https://luna.gitlab.io/discord-unofficial-docs/docs/user_settings.html#get-usersmesettings>
pub async fn get_settings(user: &mut ChorusUser) -> ChorusResult<UserSettings> {
let url_api = user.belongs_to.read().unwrap().urls.api.clone();
let request: reqwest::RequestBuilder =
Client::new().get(format!("{}/users/@me/settings", url_api));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::Global,
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<UserSettings>(user)
.await
}
/// Gets a user's profile object by their id.
///
/// This endpoint requires one of the following:
///
/// - The other user is a bot
/// - The other user shares a mutual guild with the current user
/// - The other user is a friend of the current user
/// - The other user is a friend suggestion of the current user
/// - The other user has an outgoing friend request to the current user
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-profile>
pub async fn get_profile(
user: &mut ChorusUser,
id: Snowflake,
query_parameters: GetUserProfileSchema,
) -> ChorusResult<UserProfile> {
let url_api = user.belongs_to.read().unwrap().urls.api.clone();
let request: reqwest::RequestBuilder = Client::new()
.get(format!("{}/users/{}/profile", url_api, id))
.query(&query_parameters);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::Global,
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<UserProfile>(user)
.await
}
/// Modifies the current user's profile.
///
/// Returns the updated [UserProfileMetadata].
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-user-profile>
pub async fn modify_profile(
user: &mut ChorusUser,
schema: UserModifyProfileSchema,
) -> ChorusResult<UserProfileMetadata> {
let url_api = user.belongs_to.read().unwrap().urls.api.clone();
let request: reqwest::RequestBuilder = Client::new()
.patch(format!("{}/users/@me/profile", url_api))
.json(&schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::Global,
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<UserProfileMetadata>(user)
.await
}
/// Fetches the note ([UserNote]) for the given user.
///
/// If the current user has no note for the target, this endpoint
/// returns `Err(NotFound { error: "{\"message\": \"Unknown User\", \"code\": 10013}" })`
///
/// # Reference
/// See <https://docs.discord.food/resources/user#get-user-note>
pub async fn get_note(
user: &mut ChorusUser,
target_user_id: Snowflake,
) -> ChorusResult<UserNote> {
let request = Client::new().get(format!(
"{}/users/@me/notes/{}",
user.belongs_to.read().unwrap().urls.api,
target_user_id
));
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(user);
chorus_request.send_and_deserialize_response(user).await
}
/// Sets the note for the given user.
///
/// Fires a `UserNoteUpdate` gateway event. (Note: yet to be implemented in chorus, see [#546](https://github.com/polyphony-chat/chorus/issues/546))
///
/// # Reference
/// See <https://docs.discord.food/resources/user#modify-user-note>
pub async fn set_note(
user: &mut ChorusUser,
target_user_id: Snowflake,
note: Option<String>,
) -> ChorusResult<()> {
let schema = ModifyUserNoteSchema { note };
let request = Client::new()
.put(format!(
"{}/users/@me/notes/{}",
user.belongs_to.read().unwrap().urls.api,
target_user_id
))
.json(&schema);
let chorus_request = ChorusRequest {
request,
limit_type: LimitType::default(),
}
.with_headers_for(user);
chorus_request.send_and_handle_as_result(user).await
}
}