-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy patherrors.rs
More file actions
373 lines (308 loc) · 14 KB
/
errors.rs
File metadata and controls
373 lines (308 loc) · 14 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
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
use std::borrow::Cow;
use std::error;
use derive_more::{Display, Error};
use hyper::StatusCode;
use crate::databases::database;
use crate::models::torrent::MetadataError;
use crate::tracker::service::TrackerAPIError;
use crate::utils::parse_torrent::DecodeTorrentFileError;
pub type ServiceResult<V> = Result<V, ServiceError>;
#[derive(Debug, Display, PartialEq, Eq, Error)]
#[allow(dead_code)]
pub enum ServiceError {
#[display("internal server error")]
InternalServerError,
#[display("This server is is closed for registration. Contact admin if this is unexpected")]
ClosedForRegistration,
#[display("Email is required")] //405j
EmailMissing,
#[display("Please enter a valid email address")] //405j
EmailInvalid,
#[display("The value you entered for URL is not a URL")] //405j
NotAUrl,
#[display("Invalid username/email or password")]
WrongPasswordOrUsername,
#[display("Invalid password")]
InvalidPassword,
#[display("Username not found")]
UsernameNotFound,
#[display("User not found")]
UserNotFound,
#[display("Account not found")]
AccountNotFound,
/// when the value passed contains profanity
#[display("Can't allow profanity in usernames")]
ProfanityError,
/// when the value passed contains blacklisted words
/// see [blacklist](https://github.com/shuttlecraft/The-Big-Username-Blacklist)
#[display("Username contains blacklisted words")]
BlacklistError,
/// when the value passed contains characters not present
/// in [UsernameCaseMapped](https://tools.ietf.org/html/rfc8265#page-7)
/// profile
#[display("username_case_mapped violation")]
UsernameCaseMappedError,
#[display("Password too short")]
PasswordTooShort,
#[display("Password too long")]
PasswordTooLong,
#[display("Passwords don't match")]
PasswordsDontMatch,
#[display("Couldn't send new password to the user")]
FailedToSendResetPassword,
#[display("Too many password reset requests. Try again in {remaining_secs} seconds.")]
PasswordResetLocked { remaining_secs: u64 },
#[display("Password reset locked after too many attempts. Please contact an administrator.")]
PasswordResetMaxAttemptsReached,
#[display("Too many verification email requests. Try again in {remaining_secs} seconds.")]
VerificationResendLocked { remaining_secs: u64 },
#[display("Verification email resend locked after too many attempts. Please contact an administrator.")]
VerificationResendMaxAttemptsReached,
/// when the a username is already taken
#[display("Username not available")]
UsernameTaken,
#[display("Invalid username. Usernames must consist of 1-20 alphanumeric characters, dashes, or underscore")]
UsernameInvalid,
/// email is already taken
#[display("Email not available")]
EmailTaken,
#[display("Please verify your email before logging in")]
EmailNotVerified,
/// when the a token name is already taken
/// token not found
#[display("Token not found. Please sign in.")]
TokenNotFound,
/// token expired
#[display("Token expired. Please sign in again.")]
TokenExpired,
#[display("Token invalid.")]
/// token invalid
TokenInvalid,
#[display("Uploaded torrent is not valid.")]
InvalidTorrentFile,
#[display("Uploaded torrent has an invalid pieces key.")]
InvalidTorrentPiecesLength,
#[display("Only .torrent files can be uploaded.")]
InvalidFileType,
#[display("Torrent title is too short.")]
InvalidTorrentTitleLength,
#[display("Some mandatory metadata fields are missing.")]
MissingMandatoryMetadataFields,
#[display("Selected category does not exist.")]
InvalidCategory,
#[display("Selected tag does not exist.")]
InvalidTag,
#[display("Unauthorized action.")]
UnauthorizedAction,
#[display("Unauthorized actions for guest users. Try logging in to check if you have permission to perform the action")]
UnauthorizedActionForGuests,
#[display("This torrent already exists in our database.")]
InfoHashAlreadyExists,
#[display("A torrent with the same canonical infohash already exists in our database.")]
CanonicalInfoHashAlreadyExists,
#[display("A torrent with the same original infohash already exists in our database.")]
OriginalInfoHashAlreadyExists,
#[display("This torrent title has already been used.")]
TorrentTitleAlreadyExists,
#[display("Could not whitelist torrent.")]
WhitelistingError,
#[display("Failed to send verification email.")]
FailedToSendVerificationEmail,
#[display("Category already exists.")]
CategoryAlreadyExists,
#[display("Category name cannot be empty.")]
CategoryNameEmpty,
#[display("Tag already exists.")]
TagAlreadyExists,
#[display("Tag name cannot be empty.")]
TagNameEmpty,
#[display("Torrent not found.")]
TorrentNotFound,
#[display("Category not found.")]
CategoryNotFound,
#[display("Tag not found.")]
TagNotFound,
#[display("Database error.")]
DatabaseError,
#[display("Authentication error, please sign in")]
LoggedInUserNotFound,
// Begin tracker errors
#[display("Sorry, we have an error with our tracker connection.")]
TrackerOffline,
#[display("Tracker response error. The operation could not be performed.")]
TrackerResponseError,
#[display("Tracker unknown response. Unexpected response from tracker. For example, if it can't be parsed.")]
TrackerUnknownResponse,
#[display("Torrent not found in tracker.")]
TorrentNotFoundInTracker,
#[display("Invalid tracker API token.")]
InvalidTrackerToken,
// End tracker errors
#[display("Invalid user listing fields in the URL params.")]
InvalidUserListing,
}
impl From<sqlx::Error> for ServiceError {
fn from(e: sqlx::Error) -> Self {
eprintln!("{e:?}");
if let Some(err) = e.as_database_error() {
return if err.code() == Some(Cow::from("2067")) {
if err.message().contains("torrust_torrents.info_hash") {
println!("info_hash already exists {}", err.message());
Self::InfoHashAlreadyExists
} else {
Self::InternalServerError
}
} else {
Self::TorrentNotFound
};
}
Self::InternalServerError
}
}
impl From<database::Error> for ServiceError {
fn from(e: database::Error) -> Self {
map_database_error_to_service_error(&e)
}
}
impl From<argon2::password_hash::Error> for ServiceError {
fn from(e: argon2::password_hash::Error) -> Self {
eprintln!("{e}");
Self::InternalServerError
}
}
impl From<std::io::Error> for ServiceError {
fn from(e: std::io::Error) -> Self {
eprintln!("{e}");
Self::InternalServerError
}
}
impl From<Box<dyn error::Error>> for ServiceError {
fn from(e: Box<dyn error::Error>) -> Self {
eprintln!("{e}");
Self::InternalServerError
}
}
impl From<serde_json::Error> for ServiceError {
fn from(e: serde_json::Error) -> Self {
eprintln!("{e}");
Self::InternalServerError
}
}
impl From<MetadataError> for ServiceError {
fn from(e: MetadataError) -> Self {
eprintln!("{e}");
match e {
MetadataError::MissingTorrentTitle => Self::MissingMandatoryMetadataFields,
MetadataError::InvalidTorrentTitleLength => Self::InvalidTorrentTitleLength,
}
}
}
impl From<DecodeTorrentFileError> for ServiceError {
fn from(e: DecodeTorrentFileError) -> Self {
eprintln!("{e}");
match e {
DecodeTorrentFileError::InvalidTorrentPiecesLength => Self::InvalidTorrentTitleLength,
DecodeTorrentFileError::CannotBencodeInfoDict
| DecodeTorrentFileError::InvalidInfoDictionary
| DecodeTorrentFileError::InvalidBencodeData => Self::InvalidTorrentFile,
}
}
}
impl From<TrackerAPIError> for ServiceError {
fn from(e: TrackerAPIError) -> Self {
eprintln!("{e}");
match e {
TrackerAPIError::TrackerOffline { error: _ } => Self::TrackerOffline,
TrackerAPIError::InternalServerError | TrackerAPIError::NotFound => Self::TrackerResponseError,
TrackerAPIError::TorrentNotFound => Self::TorrentNotFoundInTracker,
TrackerAPIError::UnexpectedResponseStatus
| TrackerAPIError::MissingResponseBody
| TrackerAPIError::FailedToParseTrackerResponse { body: _ } => Self::TrackerUnknownResponse,
TrackerAPIError::CannotSaveUserKey => Self::DatabaseError,
TrackerAPIError::InvalidToken => Self::InvalidTrackerToken,
}
}
}
#[must_use]
pub const fn http_status_code_for_service_error(error: &ServiceError) -> StatusCode {
#[allow(clippy::match_same_arms)]
match error {
ServiceError::ClosedForRegistration => StatusCode::FORBIDDEN,
ServiceError::EmailInvalid => StatusCode::BAD_REQUEST,
ServiceError::NotAUrl => StatusCode::BAD_REQUEST,
ServiceError::WrongPasswordOrUsername => StatusCode::FORBIDDEN,
ServiceError::InvalidPassword => StatusCode::FORBIDDEN,
ServiceError::UsernameNotFound => StatusCode::NOT_FOUND,
ServiceError::UserNotFound => StatusCode::NOT_FOUND,
ServiceError::AccountNotFound => StatusCode::NOT_FOUND,
ServiceError::ProfanityError => StatusCode::BAD_REQUEST,
ServiceError::BlacklistError => StatusCode::BAD_REQUEST,
ServiceError::UsernameCaseMappedError => StatusCode::BAD_REQUEST,
ServiceError::PasswordTooShort => StatusCode::BAD_REQUEST,
ServiceError::PasswordTooLong => StatusCode::BAD_REQUEST,
ServiceError::PasswordsDontMatch => StatusCode::BAD_REQUEST,
ServiceError::FailedToSendResetPassword => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::PasswordResetLocked { .. } => StatusCode::TOO_MANY_REQUESTS,
ServiceError::PasswordResetMaxAttemptsReached => StatusCode::TOO_MANY_REQUESTS,
ServiceError::VerificationResendLocked { .. } => StatusCode::TOO_MANY_REQUESTS,
ServiceError::VerificationResendMaxAttemptsReached => StatusCode::TOO_MANY_REQUESTS,
ServiceError::UsernameTaken => StatusCode::BAD_REQUEST,
ServiceError::UsernameInvalid => StatusCode::BAD_REQUEST,
ServiceError::EmailTaken => StatusCode::BAD_REQUEST,
ServiceError::EmailNotVerified => StatusCode::FORBIDDEN,
ServiceError::TokenNotFound => StatusCode::UNAUTHORIZED,
ServiceError::TokenExpired => StatusCode::UNAUTHORIZED,
ServiceError::TokenInvalid => StatusCode::UNAUTHORIZED,
ServiceError::TorrentNotFound => StatusCode::NOT_FOUND,
ServiceError::InvalidTorrentFile => StatusCode::BAD_REQUEST,
ServiceError::InvalidTorrentPiecesLength => StatusCode::BAD_REQUEST,
ServiceError::InvalidFileType => StatusCode::BAD_REQUEST,
ServiceError::InvalidTorrentTitleLength => StatusCode::BAD_REQUEST,
ServiceError::MissingMandatoryMetadataFields => StatusCode::BAD_REQUEST,
ServiceError::InvalidCategory => StatusCode::BAD_REQUEST,
ServiceError::InvalidTag => StatusCode::BAD_REQUEST,
ServiceError::UnauthorizedAction => StatusCode::FORBIDDEN,
ServiceError::UnauthorizedActionForGuests => StatusCode::UNAUTHORIZED,
ServiceError::InfoHashAlreadyExists => StatusCode::BAD_REQUEST,
ServiceError::CanonicalInfoHashAlreadyExists => StatusCode::CONFLICT,
ServiceError::OriginalInfoHashAlreadyExists => StatusCode::CONFLICT,
ServiceError::TorrentTitleAlreadyExists => StatusCode::BAD_REQUEST,
ServiceError::TrackerOffline => StatusCode::SERVICE_UNAVAILABLE,
ServiceError::CategoryNameEmpty => StatusCode::BAD_REQUEST,
ServiceError::CategoryAlreadyExists => StatusCode::BAD_REQUEST,
ServiceError::TagNameEmpty => StatusCode::BAD_REQUEST,
ServiceError::TagAlreadyExists => StatusCode::BAD_REQUEST,
ServiceError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::EmailMissing => StatusCode::NOT_FOUND,
ServiceError::FailedToSendVerificationEmail => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::WhitelistingError => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::DatabaseError => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::CategoryNotFound => StatusCode::NOT_FOUND,
ServiceError::TagNotFound => StatusCode::NOT_FOUND,
ServiceError::TrackerResponseError => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::TrackerUnknownResponse => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::TorrentNotFoundInTracker => StatusCode::NOT_FOUND,
ServiceError::InvalidTrackerToken => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::LoggedInUserNotFound => StatusCode::UNAUTHORIZED,
ServiceError::InvalidUserListing => StatusCode::BAD_REQUEST,
}
}
#[must_use]
pub const fn map_database_error_to_service_error(error: &database::Error) -> ServiceError {
#[allow(clippy::match_same_arms)]
match error {
database::Error::Error => ServiceError::InternalServerError,
database::Error::ErrorWithText(_) => ServiceError::InternalServerError,
database::Error::UsernameTaken => ServiceError::UsernameTaken,
database::Error::EmailTaken => ServiceError::EmailTaken,
database::Error::UserNotFound => ServiceError::UserNotFound,
database::Error::CategoryNotFound => ServiceError::InvalidCategory,
database::Error::TagAlreadyExists => ServiceError::TagAlreadyExists,
database::Error::TagNotFound => ServiceError::InvalidTag,
database::Error::TorrentNotFound => ServiceError::TorrentNotFound,
database::Error::TorrentAlreadyExists => ServiceError::InfoHashAlreadyExists,
database::Error::TorrentTitleAlreadyExists => ServiceError::TorrentTitleAlreadyExists,
database::Error::UnrecognizedDatabaseDriver => ServiceError::InternalServerError,
database::Error::TorrentInfoHashNotFound => ServiceError::TorrentNotFound,
}
}