ignite_core/media.rs
1//! The media library that [`Image`](crate::FieldKind::Image),
2//! [`File`](crate::FieldKind::File) and [`Gallery`](crate::FieldKind::Gallery) fields pick
3//! from.
4//!
5//! Ignite assumes no storage, table or upload path: the app implements [`MediaLibrary`]
6//! and registers it with [`Registries::register_media_library`], as Laravel binds an implementation to
7//! a contract. A media field stores item ids. With a library registered, the panel shows
8//! the stored items and refuses an id the library does not have. With none, the fields
9//! still render, and their ids are checked as positive whole numbers only.
10//!
11//! ```ignore
12//! registries.register_media_library(Attachments);
13//! ```
14
15use std::sync::{Arc, PoisonError};
16
17use crate::registries::Registries;
18
19use orbit_orm::Database;
20use serde::Serialize;
21
22use crate::RuntimeFuture;
23
24/// One item of the media library, as a form shows it.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
26pub struct MediaItem {
27 /// The item's id, as a media field stores it.
28 pub id: i64,
29 /// The item's title, shown next to it.
30 pub title: String,
31 /// A URL that shows the item: the image itself, or the file to download.
32 pub url: String,
33}
34
35/// The app's media library. Implement it and add it with [`Registries::register_media_library`].
36pub trait MediaLibrary: Send + Sync + 'static {
37 /// The items among `ids` that exist, in any order. An id with no item is left out.
38 fn find<'a>(&'a self, db: &'a Database, ids: &'a [i64]) -> RuntimeFuture<'a, Vec<MediaItem>>;
39
40 /// The URL of the page where a user browses and uploads media, which the form links to
41 /// so the user can find an item's id. The default is none.
42 fn browse_url(&self) -> Option<String> {
43 None
44 }
45}
46
47impl Registries {
48 /// Sets the media library that media fields use, from the next request on. Registering
49 /// again replaces it.
50 pub fn register_media_library(&self, library: impl MediaLibrary) {
51 *self
52 .inner
53 .media
54 .write()
55 .unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(library));
56 }
57
58 /// The registered media library, if the app registered one.
59 pub fn media_library(&self) -> Option<Arc<dyn MediaLibrary>> {
60 self.inner
61 .media
62 .read()
63 .unwrap_or_else(PoisonError::into_inner)
64 .clone()
65 }
66}
67
68/// Sets the media library of the default app, as 0.7.1 did. See
69/// [`Registries::register_media_library`](crate::Registries::register_media_library).
70pub fn register_media_library(library: impl MediaLibrary) {
71 Registries::default_app().register_media_library(library);
72}
73
74/// The media library of the default app. See
75/// [`Registries::media_library`](crate::Registries::media_library).
76pub fn media_library() -> Option<Arc<dyn MediaLibrary>> {
77 Registries::default_app().media_library()
78}