shared/domain/image.rs
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
//! Types for images.
pub mod recent;
pub mod tag;
pub mod user;
use crate::api::endpoints::PathPart;
use super::{
category::CategoryId,
meta::{AffiliationId, AgeRangeId, ImageStyleId, ImageTagIndex},
Publish,
};
use chrono::{DateTime, Utc};
use macros::make_path_parts;
use serde::{Deserialize, Serialize};
#[cfg(feature = "backend")]
use sqlx::{postgres::PgRow, types::Json};
use std::collections::HashMap;
make_path_parts!(ImageGetPath => "/v1/image/{}" => ImageId);
/// Represents different sizes of images
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
#[cfg_attr(feature = "backend", derive(sqlx::Type))]
#[repr(i16)]
pub enum ImageSize {
/// The image is a canvas (background) image
Canvas = 0,
/// The image is a sticker.
Sticker = 1,
/// The image is a user profile picture
// TODO: Rename since it's also used for circles and schools
UserProfile = 2,
}
impl ImageSize {
/// The size of a thumbnail (Width x Height pixels).
pub const THUMBNAIL_SIZE: (u32, u32) = (256, 144);
/// Gets the proper size of the image once resized.
#[must_use]
pub const fn size(self) -> (u32, u32) {
match self {
Self::Canvas => (1920, 1080),
Self::Sticker => (1440, 810),
Self::UserProfile => (256, 256),
}
}
/// Returns self represented by a string
#[must_use]
pub const fn to_str(self) -> &'static str {
match self {
Self::Canvas => "Canvas",
Self::Sticker => "Sticker",
Self::UserProfile => "UserProfile",
}
}
}
wrap_uuid! {
/// Wrapper type around [`Uuid`], represents the ID of a image.
///
/// [`Uuid`]: ../../uuid/struct.Uuid.html
pub struct ImageId
}
make_path_parts!(ImageCreatePath => "/v1/image");
// todo: # errors doc section
/// Request to create a new image.
#[derive(Serialize, Deserialize, Debug)]
pub struct ImageCreateRequest {
/// The name of the image.
pub name: String,
/// The description of the image.
pub description: String,
/// Is the image premium?
pub is_premium: bool,
/// When to publish the image.
///
/// If [`Some`] publish the image according to the `Publish`. Otherwise, don't publish it.
pub publish_at: Option<Publish>,
/// The image's styles.
pub styles: Vec<ImageStyleId>,
/// The image's age ranges.
pub age_ranges: Vec<AgeRangeId>,
/// The image's affiliations.
pub affiliations: Vec<AffiliationId>,
/// The image's tags.
pub tags: Vec<ImageTagIndex>,
/// The image's categories.
pub categories: Vec<CategoryId>,
/// What kind of image this is.
pub size: ImageSize,
}
make_path_parts!(ImageUpdatePath => "/v1/image/{}" => ImageId);
// todo: # errors doc section.
#[derive(Serialize, Deserialize, Debug, Default)]
/// Request to update an image.
///
/// All fields are optional, any field that is [`None`] will not be updated.
pub struct ImageUpdateRequest {
/// If `Some` change the image's name to this name.
#[serde(default)]
pub name: Option<String>,
/// If `Some` change the image's description to this description.
#[serde(default)]
pub description: Option<String>,
/// If `Some` mark the image as premium or not.
#[serde(default)]
pub is_premium: Option<bool>,
/// If `Some`, change the `publish_at` to the given `Option<Publish>`.
///
/// Specifically, if `None`, don't update.
/// If `Some(None)`, set the `publish_at` to `None`, unpublishing it if previously published.
/// Otherwise set it to the given [`Publish`].
///
/// [`Publish`]: struct.Publish.html
#[serde(deserialize_with = "super::deserialize_optional_field")]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub publish_at: Option<Option<Publish>>,
/// If `Some` replace the image's styles with these.
#[serde(default)]
pub styles: Option<Vec<ImageStyleId>>,
/// If `Some` replace the image's age ranges with these.
#[serde(default)]
pub age_ranges: Option<Vec<AgeRangeId>>,
/// If `Some` replace the image's affiliations with these.
#[serde(default)]
pub affiliations: Option<Vec<AffiliationId>>,
/// If `Some` replace the image's categories with these.
#[serde(default)]
pub categories: Option<Vec<CategoryId>>,
/// If `Some` replace the image's tags with these.
#[serde(default)]
pub tags: Option<Vec<ImageTagIndex>>,
}
make_path_parts!(ImageSearchPath => "/v1/image");
/// Search for images via the given query string.
///
/// * `kind` field must match the case as represented in the returned json body (`PascalCase`?).
/// * Vector fields, such as `age_ranges` should be given as a comma separated vector (CSV).
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct ImageSearchQuery {
/// The query string.
#[serde(default)]
pub q: String,
/// Optionally filter by `kind`
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<ImageSize>,
/// The page number of the images to get.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
/// Optionally filter by `image_styles`
#[serde(default)]
#[serde(serialize_with = "super::csv_encode_uuids")]
#[serde(deserialize_with = "super::from_csv")]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub styles: Vec<ImageStyleId>,
/// Optionally filter by `age_ranges`
#[serde(default)]
#[serde(serialize_with = "super::csv_encode_uuids")]
#[serde(deserialize_with = "super::from_csv")]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub age_ranges: Vec<AgeRangeId>,
/// Optionally filter by `affiliations`
#[serde(default)]
#[serde(serialize_with = "super::csv_encode_uuids")]
#[serde(deserialize_with = "super::from_csv")]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub affiliations: Vec<AffiliationId>,
/// Optionally filter by `categories`
#[serde(default)]
#[serde(serialize_with = "super::csv_encode_uuids")]
#[serde(deserialize_with = "super::from_csv")]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<CategoryId>,
/// Optionally filter by `tags`
#[serde(default)]
#[serde(serialize_with = "super::csv_encode_i16_indices")]
#[serde(deserialize_with = "super::from_csv")]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<ImageTagIndex>,
/// Optionally order by `tags`, given in decreasing priority.
///
/// # Notes on priority
/// Consider a request with 4 tags, `[clothing, food, red, sports]`.
///
/// "Priority ordering" means that all items tagged as `clothing` will appear before those
/// without it, and that `[clothing, food]` will appear before `[clothing]` or `[clothing, red]`.
///
/// ## Assigning scores
/// The priority is achieved by using Algolia's [filter scoring](https://www.algolia.com/doc/guides/managing-results/refine-results/filtering/in-depth/filter-scoring/) feature with `"sumOrFiltersScore": true`.
///
/// Scores are weighted exponentially by a factor of 2. The lowest priority tag is given a score of 1,
/// and the `i`th highest priority tag is given a score of `2.pow(i)`. This assignment is *provably*
/// correct that we get the desired ranking. This can also be interpreted as bit vector with comparison.
///
/// *NOTE*: this means that with `i64` range supported by Algolia, we can only assign priority for
/// the first 62 tags. The remaining are all given a score of 1.
///
/// ## Example
/// For an example request `[clothing, food, red, sports]`, we assign the scores:
///
/// | tag name | score | (truncated) bit vector score |
/// |-----------|-------|-------------------------------|
/// | clothing | 8 | `0b_1000` |
/// | food | 4 | `0b_0100` |
/// | red | 2 | `0b_0010` |
/// | sports | 1 | `0b_0001` |
///
/// This means that the entries will be returned in the following order, based on their tags:
///
/// | position | entry name | tag names | score | (truncated) bit vector score |
/// |-----------|------------|--------------|-------|-------------------------------|
/// | 0 | hat | clothing | 8 | `0b_1000` |
/// | 1 | cherry | red, food | 6 | `0b_0110` |
/// | 2 | cucumber | green, food | 4 | `0b_0100` |
/// | 3 | stop sign | red | 2 | `0b_0010` |
/// | 4 | basketball | sports | 1 | `0b_0001` |
/// | 5 | wallet | [no tags] | 0 | `0b_0000` |
#[serde(default)]
#[serde(serialize_with = "super::csv_encode_i16_indices")]
#[serde(deserialize_with = "super::from_csv")]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tags_priority: Vec<ImageTagIndex>,
/// Optionally filter by `is_premium`
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub is_premium: Option<bool>,
/// Optionally filter by `is_published`
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub is_published: Option<bool>,
/// The limit of results per page.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub page_limit: Option<u32>,
}
/// Response for successful search.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ImageSearchResponse {
/// the images returned.
pub images: Vec<ImageResponse>,
/// The number of pages found.
pub pages: u32,
/// The total number of images found
pub total_image_count: u64,
}
make_path_parts!(ImageBrowsePath => "/v1/image/browse");
/// Query for [`Browse`](crate::api::endpoints::image::Browse).
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct ImageBrowseQuery {
/// Optionally filter by `is_published`
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub is_published: Option<bool>,
/// Optionally filter by `size`
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<ImageSize>,
/// The page number of the images to get.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
/// The limit of results per page.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub page_limit: Option<u32>,
}
/// Response for [`Browse`](crate::api::endpoints::image::Browse).
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ImageBrowseResponse {
/// the images returned.
pub images: Vec<ImageResponse>,
/// The number of pages found.
pub pages: u32,
/// The total number of images found
pub total_image_count: u64,
}
/// Response for getting a single image.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ImageResponse {
/// The image metadata.
pub metadata: ImageMetadata,
}
make_path_parts!(ImageUploadPath => "/v1/image/{}/raw" => ImageId);
// #[allow(missing_docs)]
// #[derive(Clone, Debug)]
// pub struct ImageUploadPath<'a>(&'a ImageId);
// impl crate::api::endpoints::PathParts for ImageUploadPath<'_> {
// const PATH: &'static str = "/v1/image/{ImageId}/raw";
// fn get_filled(&self) -> String {
// let mut src = String::from(Self::PATH);
// src = src.replace(<ImageId>::PLACEHOLDER, &self.0.get_path_string());
// src
// }
// }
/// Request to indicate the size of an image for upload.
#[derive(Serialize, Deserialize, Debug)]
pub struct ImageUploadRequest {
/// The size of the image to be uploaded in bytes. Allows the API server to check that the file size is
/// within limits and as a verification at GCS that the entire file was uploaded
pub file_size: usize,
}
/// URL to upload an image. Supports resumable uploading.
#[derive(Serialize, Deserialize, Debug)]
pub struct ImageUploadResponse {
/// The session URI used for uploading, including the query for uploader ID
pub session_uri: String,
}
/// Over the wire representation of an image's metadata.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ImageMetadata {
/// The image's ID.
pub id: ImageId,
/// The name of the image.
pub name: String,
/// A string describing the image.
pub description: String,
/// A translated descriptions of the image.
pub translated_description: HashMap<String, String>,
/// Whether or not the image is premium.
pub is_premium: bool,
/// What size of image this is.
pub size: ImageSize,
/// When the image should be considered published (if at all).
pub publish_at: Option<DateTime<Utc>>,
/// The styles associated with the image.
pub styles: Vec<ImageStyleId>,
/// The tags associated with the image.
pub tags: Vec<ImageTagIndex>,
/// The age ranges associated with the image.
pub age_ranges: Vec<AgeRangeId>,
/// The affiliations associated with the image.
pub affiliations: Vec<AffiliationId>,
/// The categories associated with the image.
pub categories: Vec<CategoryId>,
/// When the image was originally created.
pub created_at: DateTime<Utc>,
/// When the image was last updated.
pub updated_at: Option<DateTime<Utc>>,
}
/// Response for successfully creating a Image.
pub type CreateResponse = super::CreateResponse<ImageId>;
// HACK: we can't get `Vec<_>` directly from the DB, so we have to work around it for now.
// see: https://github.com/launch/sqlx/issues/298
#[cfg(feature = "backend")]
impl<'r> sqlx::FromRow<'r, PgRow> for ImageMetadata {
fn from_row(row: &'r PgRow) -> Result<Self, sqlx::Error> {
let DbImage {
id,
size,
name,
description,
translated_description,
is_premium,
publish_at,
styles,
age_ranges,
affiliations,
categories,
tags,
created_at,
updated_at,
} = DbImage::from_row(row)?;
Ok(Self {
id,
size,
name,
description,
translated_description: translated_description.0,
is_premium,
publish_at,
styles: styles.into_iter().map(|(it,)| it).collect(),
age_ranges: age_ranges.into_iter().map(|(it,)| it).collect(),
affiliations: affiliations.into_iter().map(|(it,)| it).collect(),
categories: categories.into_iter().map(|(it,)| it).collect(),
tags: tags.into_iter().map(|(it,)| it).collect(),
created_at,
updated_at,
})
}
}
#[cfg_attr(feature = "backend", derive(sqlx::FromRow))]
#[cfg(feature = "backend")]
struct DbImage {
pub id: ImageId,
pub size: ImageSize,
pub name: String,
pub description: String,
pub translated_description: Json<HashMap<String, String>>,
pub is_premium: bool,
pub publish_at: Option<DateTime<Utc>>,
pub styles: Vec<(ImageStyleId,)>,
pub age_ranges: Vec<(AgeRangeId,)>,
pub affiliations: Vec<(AffiliationId,)>,
pub categories: Vec<(CategoryId,)>,
pub tags: Vec<(ImageTagIndex,)>,
pub created_at: DateTime<Utc>,
pub updated_at: Option<DateTime<Utc>>,
}
make_path_parts!(ImageDeletePath => "/v1/image/{}" => ImageId);
make_path_parts!(ImagePutPath => "/v1/image/{}/use" => ImageId);