use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::entry::{FileAttachment, SessionEntry};
use crate::constants::{INLINE_IMAGE_MEDIA_TYPES, MAX_ENTRIES_RANGE_LIMIT};
use crate::error::ValidationError;
use crate::payload::{require_integer, require_string};
pub const DEFAULT_ENTRIES_LIMIT: u64 = 50;
const MAX_BEFORE: u64 = 9_007_199_254_740_991;
const SESSION_ID_MAX_BYTES: usize = 64;
const ATTACHMENT_ID_MAX_BYTES: usize = 128;
pub fn load_session_id(payload: &Map<String, Value>) -> Result<String, ValidationError> {
require_string(payload.get("sessionId"), "sessionId", SESSION_ID_MAX_BYTES)
}
pub fn find_attachment_id(payload: &Map<String, Value>) -> Result<String, ValidationError> {
require_string(
payload.get("attachmentId"),
"attachmentId",
ATTACHMENT_ID_MAX_BYTES,
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntriesRangeRequest {
pub before: Option<u64>,
pub limit: u64,
}
pub fn entries_range(payload: &Map<String, Value>) -> Result<EntriesRangeRequest, ValidationError> {
let before = match payload.get("before") {
None => None,
Some(value) => Some(require_integer(Some(value), "before", 0, MAX_BEFORE)?),
};
let limit = match payload.get("limit") {
None => DEFAULT_ENTRIES_LIMIT,
Some(value) => require_integer(Some(value), "limit", 1, MAX_ENTRIES_RANGE_LIMIT as u64)?,
};
Ok(EntriesRangeRequest { before, limit })
}
impl EntriesRangeRequest {
pub fn resolve(&self, total: u64) -> (u64, u64) {
let end = self.before.map_or(total, |before| before.min(total));
let start = end.saturating_sub(self.limit);
(start, end)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InlineAttachment {
pub path: String,
pub media_type: String,
}
pub fn find_inline_attachment<'a>(
entries: &'a [SessionEntry],
id: &str,
) -> Option<&'a FileAttachment> {
entries
.iter()
.filter_map(|entry| match entry {
SessionEntry::User {
attachments: Some(files),
..
} => Some(files.as_slice()),
_ => None,
})
.flatten()
.find(|file| file.id == id && INLINE_IMAGE_MEDIA_TYPES.contains(&file.media_type.as_str()))
}