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
use chrono::{FixedOffset, Utc};
use crypto::digest::Digest;
use crypto::md5::Md5;
use rocket::http::{ContentType, Status};
use rocket::serde::json::Json;
use rocket::{Build, Rocket};
use rocket_db_pools::Connection;
use sea_orm::{entity::*, ActiveModelTrait};
use crate::config::storage::*;
use crate::db::{self, image, prelude::*};
use crate::models::error::*;
use crate::models::storage::{ReferrerCheck, SaveImage};
use crate::pool::{MinioImageStorage, PgDb};
use crate::utils::auth::Auth;
pub async fn init(rocket: Rocket<Build>) -> Rocket<Build> {
rocket.mount(
"/storage",
routes![upload_image, download_image, get_images],
)
}
#[post("/images", data = "<image>")]
async fn upload_image(
auth: Auth,
db: Connection<PgDb>,
bucket: Connection<MinioImageStorage>,
image: SaveImage,
) -> (Status, Result<String, Json<ErrorResponse>>) {
info!("[IMAGE] User {} id uploading image.", auth.id);
let pg_con = db.into_inner();
let mut hash_md5 = Md5::new();
hash_md5.input(image.content.as_slice());
let filename = hash_md5.result_str() + "." + image.content_type.to_string().as_str();
let image_size = image.content.len() as i32;
if image_size == 0 {
return (
Status::BadRequest,
Err(Json(ErrorResponse::build(
ErrorCode::EmptyField,
"Image is empty",
))),
);
}
match UserStatus::find_by_id(auth.id).one(&pg_con).await {
Ok(opt_state) => match opt_state {
Some(state) => {
if state.file_num >= *MAX_IMAGE_NUM {
return (
Status::TooManyRequests,
Err(Json(ErrorResponse::build(
ErrorCode::RateLimit,
"Store too many images.",
))),
);
}
match bucket
.put_object(filename.as_str(), image.content.as_slice())
.await
{
Ok((_, 200)) => {
let now = Utc::now().with_timezone(&FixedOffset::east(8 * 3600));
let record = image::ActiveModel {
filename: Set(filename.to_owned()),
uid: Set(auth.id),
size: Set(image_size),
create_time: Set(now.to_owned()),
last_download_time: Set(now),
..Default::default()
};
let file_num = state.file_num;
let file_capacity = state.file_capacity;
let mut ust: db::user_status::ActiveModel = state.into();
ust.file_num = Set(file_num + 1);
ust.file_capacity = Set(file_capacity + image_size as i64);
let _ = record.insert(&pg_con).await;
let _ = ust.update(&pg_con).await;
(Status::Ok, Ok(filename))
}
Ok((_, code)) => (
Status::InternalServerError,
Err(Json(ErrorResponse::build(
ErrorCode::Unknown,
format!("code: {}", code),
))),
),
Err(e) => {
log::error!("[Image-Storage] Database Error {:?}", e);
(
Status::InternalServerError,
Err(Json(ErrorResponse::default())),
)
}
}
}
None => {
info!("[Image-Storage] Cannot find user_status by uid.");
(
Status::BadRequest,
Err(Json(ErrorResponse::build(ErrorCode::UserNotExist, ""))),
)
}
},
Err(e) => {
error!("[Image-Storage] Database Error: {:?}", e);
(
Status::InternalServerError,
Err(Json(ErrorResponse::default())),
)
}
}
}
#[get("/images/<filename>")]
async fn download_image(
auth: Auth,
_ref: ReferrerCheck,
db: Connection<PgDb>,
bucket: Connection<MinioImageStorage>,
filename: &str,
) -> (Status, (ContentType, Result<Vec<u8>, Json<ErrorResponse>>)) {
info!("[IMAGE] User {} id downloading image.", auth.id);
let (data, code) = bucket.get_object(filename).await.unwrap();
match code {
200 => {
let pg_con = db.into_inner();
let record = image::ActiveModel {
filename: Set(filename.to_owned()),
last_download_time: Set(Utc::now().with_timezone(&FixedOffset::east(8 * 3600))),
..Default::default()
};
let _ = record.update(&pg_con).await;
match filename.split('.').last().unwrap() {
"png" => (Status::Ok, (ContentType::PNG, Ok(data))),
"gif" => (Status::Ok, (ContentType::GIF, Ok(data))),
_ => (Status::Ok, (ContentType::JPEG, Ok(data))),
}
}
_ => (
Status::NotFound,
(
ContentType::JSON,
Err(Json(ErrorResponse::build(ErrorCode::FileNotExist, ""))),
),
),
}
}
#[get("/images")]
async fn get_images(
auth: Auth,
db: Connection<PgDb>,
bucket: Connection<MinioImageStorage>,
) -> (
Status,
Result<Json<Vec<Vec<(String, u64)>>>, Json<ErrorResponse>>,
) {
let pg_con = db.into_inner();
match Admin::find_by_id(auth.id).one(&pg_con).await {
Ok(admin) => match admin {
Some(_) => {
info!("[IMAGE] User {} id fetching image list.", auth.id);
let bucket_list = bucket.list("/".to_owned(), Some("/".to_owned())).await;
match bucket_list {
Ok(list) => {
let results: Vec<Vec<(String, u64)>> = list
.iter()
.map(|item| {
let r: Vec<(String, u64)> = item
.contents
.iter()
.map(|c| (c.key.to_owned(), c.size))
.collect();
r
})
.collect();
(Status::Ok, Ok(Json(results)))
}
Err(e) => {
log::error!("[Image-Storage] Database Error {:?}", e);
(
Status::InternalServerError,
Err(Json(ErrorResponse::default())),
)
}
}
}
None => (
Status::Forbidden,
Err(Json(ErrorResponse::build(
ErrorCode::UserForbidden,
"Permission denied.",
))),
),
},
Err(e) => {
log::error!("[ADMIN] Database Error: {:?}", e);
(
Status::InternalServerError,
Err(Json(ErrorResponse::default())),
)
}
}
}