redseat-api
Rust client for Redseat media servers. Work in progress.
let cloud = http?;
let session = cloud.sign_in_with_google_id_token.await?;
let servers = cloud.list_servers.await?;
let client = connect_http.await?;
let server = new;
let libraries = server.get_libraries.await?;
let page = server.library
.get_medias_page
.await?;
A media's file: library.get_media(&media, &MediaFileQuery::default()) downloads it whole (decrypted in an encrypted library), and library.media_url(&media.id, ...) gives its URL with a server token, for a video player that streams it with range requests. In an encrypted library, library.open_encrypted_media(&media) reads its plaintext by ranges (read_at), decrypting only what is read.
Lists for a sync: get_tags, get_people, get_series, get_movies, get_episodes and get_books take the server's queries; with after, only what was modified strictly after it comes back, paged with limit and offset. get_deleted lists deletions the same way.
The other calls of a library, and of a server (ping, get_history):
| Calls | |
|---|---|
| Tags | create_tag, update_tag (rename, move, alternative names, external ids), merge_tag, remove_tag |
| People | get_person, create_person, update_person, remove_person, merge_people, get_movie_people, get_serie_people, get_book_people |
| Series | create_serie, update_serie, remove_serie, set_episode_watched, set_episode_progress, add_searched_episode_media |
| Movies | create_movie, update_movie, remove_movie, set_movie_watched, set_movie_progress, add_searched_movie_media |
| Books | get_book, create_book, update_book, remove_book, set_book_watched, update_book_poster |
| Medias | get_media_metadata, get_media_by_hash, update_media, set_media_progress, remove_medias, media_share_url, download_medias, download_medias_in_background |
| Channels | get_channels, add_tag_to_channel, remove_tag_from_channel, channel_stream_url, channel_hls_url, stop_channel_hls |
| Images | get_serie_image, get_episode_image, get_movie_image, get_book_image, get_person_image, get_channel_image (bytes), channel_image_url |
| Requests through plugins | process_request, process_request_bytes, check_request_permanent, add_request, request_share_url |
| Searches through plugins, as streams | search_movies_stream, search_series_stream, search_books_stream, search_people_stream (metadata), search_movie_medias_stream, search_episode_medias_stream, search_book_medias_stream (files) |
A search stream gives what each source (plugin) found as it answers, and ends when all did:
use StreamExt;
let lookup = RsLookupMovie ;
let mut results = library.search_movies_stream.await?;
while let Some = results.next.await
Ids, flags and dates are plain arguments; items to create (TagForAdd, PersonForAdd), their changes (TagForUpdate, MediaForUpdate...), image options (ImageRequestOptions) and requests (RsRequest, RsGroupDownload, in redseat_api::rs_plugin_common_interfaces::request) are the server's types.
Coming from the TypeScript client @redseat/api, where a call has no method of the same name here:
| TypeScript | Rust |
|---|---|
setKey(passphrase) |
library.set_passphrase(passphrase) |
decryptMedia(passphrase, data, iv) |
library.decrypt_thumb(&media, &data) once the passphrase is set, or crypto::decrypt_buffer(&crypto::derive_key(passphrase), &iv, &data) |
encryptText(passphrase, text) |
crypto::encrypt_text(&crypto::derive_text_key(passphrase), text) |
decryptText(passphrase, text) |
crypto::decrypt_text(&crypto::derive_text_key(passphrase), text) |
renameTag, tagChangeParent, tagAddAlt, tagRemoveAlt, tagAddOtherId, tagRemoveOtherId |
update_tag with the matching field of TagForUpdate |
getAllEpisodes(query) |
get_episodes, paged with limit and offset |
mediaUpdateProgress |
set_media_progress |
uploadGroup(download, { spawn }) |
download_medias, or download_medias_in_background with spawn |
processRequestBlob |
process_request_bytes |
getMediaShareUrl, getRequestShareUrl |
media_share_url, request_share_url |
getChannelStreamUrl, getChannelHlsUrl, getChannelImageUrl |
channel_stream_url, channel_hls_url, channel_image_url (AuthorizedUrl: the token is apart from the URL) |
client.get('/libraries/:id/<kind>/:id/image?...') |
get_serie_image, get_movie_image... with ImageRequestOptions |
client.getFullUrl(path) with getValidAuthToken() |
client.authorized_url(path, &[]) |
Calls from a host that sends requests itself
Each call also comes without its I/O, for a host that cannot run the async client (a WebAssembly module that may not block or run async code, a binding to another language): a Call<T> holds the Request to send and reads its Response into the typed result. server::calls, library::calls (the library id first) and cloud::calls build them; the async methods are these same calls run by RedseatClient::run and CloudClient::run. They need no feature, on every target.
use calls;
let call = get_tags?;
// The async client: the token is added and refreshed for you.
let tags = client.run.await?;
// A host that sends the request itself: add the server token, send, read the answer.
let call = get_tags?;
let request = call.request.clone.bearer; // path relative to the server
let response = send; // the host's own HTTP: status, body
let tags = call.parse?; // any status: 401 is ErrorKind::Unauthorized
- Requests to a server carry no token. A host gets one with
cloud::calls::fetch_server_token, asks for a new one whenServerToken::expires_within(now, margin)says so, and after a refusal (ErrorKind::Unauthorized) sends the request once more with a new token:parsereads the second answer too.Request'sDebughides theAuthorizationheader. - The cloud sign-in is two requests:
cloud::calls::sign_in_with_google_id_tokenexchanges the Google ID token, and its answer is the second call, which reads the new session back. - Files come as the server sends them: in an encrypted library, decrypt a thumbnail (
get_thumb_raw) or a file (get_media_file) withlibrary::decrypt_media_data. - Async only: the URLs with a token (
media_url,channel_*_url) and the share URLs (they need the transport's base URL),set_passphrase(several requests and a check),get_thumbandget_media(a call then the decryption), reading encrypted media by ranges, the event and search streams, the mirror and the Google desktop sign-in.
Mirror (features mirror and sqlite)
A local copy of a server's libraries, kept in sync in the background and read at once, offline too, like the Redseat phone app does.
mirroris the sync engine and its storage traits:MirrorStore(the items),ThumbStore(thumbnail bytes) andRuntime(tasks and timers). An app can store the copy anywhere (the host's SQLite, IndexedDB...) withMirror::with_parts.sqliteadds ours:SqliteStore(bundled SQLite),Mirror::openandServerCopy::open. Leave it out when the app links its own SQLite, so one build never carries two.
use ;
let mut options = new;
options.thumbs_limit = 2 * 1024 * 1024 * 1024; // thumbnail cache: 2 GB
let mirror = open.await?; // reads work now, offline too
mirror.connect; // ServerApi: sync every library, live events
mirror.set_priority; // the library on screen syncs first
let mut events = mirror.subscribe; // Changed { library, changes }, Sync { .. }, ...
let count = mirror.count_medias.await?;
let medias = mirror.medias_at.await?;
let thumb = mirror.thumb.await?; // disk cache, fetched once
mirror.disconnect; // sign-out: stop syncing, keep the data
- Everything per library: medias, tags, people, series, movies, episodes and books, with their relations, and the library list. One file per server, at the path the app gives; thumbnails go in a
thumbsfolder next to it. - The first sync is full; later ones fetch what changed since the last one (with a 1 ms overlap) and apply the deletions. Live events are applied as they come, and a reconnection catches up. A lost sync state means one full repair.
- Encrypted libraries are stored as the server sends them;
set_passphrasethen decrypts thumbnails on read. They stay encrypted on disk. - Hidden libraries (a per-user preference on the server) are kept with
hiddenset;set_library_hiddenhides or shows one again, on the server then in the local copy. Mirror::openis for native targets: SQLite, thumbnail files and tokio.Mirror::with_partstakes the app's ownMirrorStore(items),ThumbStore(thumbnail bytes) andRuntime(background tasks and timers), for another runtime or forwasm32-unknown-unknown. This crate has no web implementation of them yet.
App state (feature app)
The state every Redseat app shows, so each app (GPUI on desktop, Exact, native mobile apps through bindings) only draws it. Apps read it, and read it again when a Change says it changed. app alone is details, text, tracks and TokenStore, with no other dependency; ServerCopy comes with mirror (and ServerCopy::open with sqlite).
use ;
let copy = open.await?; // on tokio; `copy` is a cheap handle, clone it for each screen
copy.connect;
let libraries = copy.libraries.await?; // sidebar order: by type, then name
copy.focus; // the library on screen syncs first
let view = copy.library.await?; // count, revision, sync progress
let medias = copy.medias.await?; // newest first
match copy.reach
ServerCopy: a server through its mirror. The connection runs in the background (reach: connecting, connected, offline with or without a Retry).focussays which library the person looks at (it syncs first); reads never change it, so several screens can show several libraries.librarygives aLibraryView: while the library syncs its count and revision hold still, so the grid does not jump; a new revision (sync ended, count changed, events missed) means reading the medias again; a first copy or a sync of more than 500 medias shows its progress instead (copying).renew_basegets a new token after a download's 401. Reads, all from the copy:mediasandcountwith aMediaQuery(grid_query()is the grid's: newest first),media, the lists (people,tags,series,episodes,movies,books), one item by id (person,tag,serie,episode,movie,book), andrelated(library, media): a zoomed media's people, tags, series with the episode, movies and books in one call. Alsonames(people and tags for the details),baseandlocate(where files are downloaded, the token apart;locate(.., fresh: true)gets a new token after a refusal),sync_summary(a status bar's words).Change:Server(library list, connection, address and token),Library { library, items }(its count or sync, and the ids of each kind that changed),All(changes were missed). Told on the runtime's threads, grouped over 250 ms.itemsmaps each kind toIds::Listed(the net added, updated and removed ids over the burst) orIds::Many(more thanMAX_IDS, 1000: read them all again); it is empty when only the sync moved on. A grid can patch its cells from them (ServerCopy::mediareads one): an updated media keeps its place unless its date changed, an added or removed one moves those after it. Each view picks the kinds it shows:change.ids(SyncKind::People)gives the people that changed (Nonewhen none did,Ids::ManyafterAll),change.touches(kind)whether any may have.TokenStore: the cloud session token between runs (the OS credential store). A session controller that runs restore, sign-in and sign-out is planned (#20).details(a media's details as rows) andtext(durations, sizes, initials, the sync's progress, cloud errors).tracks: a video's audio and subtitle tracks, from what a player engine says of them (TrackDetails): their labels ("English · Dolby Digital Plus 5.1", "French (Forced)") and the ones to play first (choose_audio,choose_subtitle: the original language's audio, subtitles in the viewer's language, forced only when the audio is in it), following the viewer's earlier picks (TrackChoice).downloads(native): movie and episode files kept offline (Downloads::open, orDownloads::open_nativeon mobile to hand byte transfers to iOSURLSession/ AndroidWorkManagerwhile keeping the queue, progress, pause/resume, retries, page and on-the-fly encrypted playback shared) and saved copies (save_copy).- Builds on every target,
wasm32-unknown-unknownincluded withoutwasm-bindgen:ServerCopy::with_mirrortakes the app's own mirror and runtime.
Desktop apps can get the Google ID token with google::GoogleSignIn (browser sign-in with a loopback redirect and PKCE). See examples/sign_in.rs.
- Data types are the server's own, from
rs-plugin-common-interfaces(redseat_api::types). - Encrypted libraries use the server's own implementation, from
redseat-crypto(redseat_api::crypto). - Builds for
wasm32-unknown-unknown. UniFFI and wasm-bindgen bindings are planned. - On wasm, the feature
js(implied byhttp) takes the clock and random numbers from the browser, throughwasm-bindgen. Without it (default-features = false, with or withoutmirror), nothing bringswasm-bindgen, for a host that refuses its imports (Expo's Exact). The host then gives both: the random numbers through a getrandom backend (build with--cfg getrandom_backend="custom", see the getrandom docs), and the clock withredseat_api::set_clock(now_ms), once at start. Without a clock the time is 0: a server token is refreshed only after a 401, and the mirror's repair sync removes no stale items and reportsSynced(0).
Licensed under MIT or Apache-2.0, at your option.