openbutler_protocol/session/
read.rs1use serde::{Deserialize, Serialize};
11use serde_json::{Map, Value};
12
13use super::entry::{FileAttachment, SessionEntry};
14use crate::constants::{INLINE_IMAGE_MEDIA_TYPES, MAX_ENTRIES_RANGE_LIMIT};
15use crate::error::ValidationError;
16use crate::payload::{require_integer, require_string};
17
18pub const DEFAULT_ENTRIES_LIMIT: u64 = 50;
20
21const MAX_BEFORE: u64 = 9_007_199_254_740_991;
23const SESSION_ID_MAX_BYTES: usize = 64;
25const ATTACHMENT_ID_MAX_BYTES: usize = 128;
26
27pub fn load_session_id(payload: &Map<String, Value>) -> Result<String, ValidationError> {
29 require_string(payload.get("sessionId"), "sessionId", SESSION_ID_MAX_BYTES)
30}
31
32pub fn find_attachment_id(payload: &Map<String, Value>) -> Result<String, ValidationError> {
34 require_string(
35 payload.get("attachmentId"),
36 "attachmentId",
37 ATTACHMENT_ID_MAX_BYTES,
38 )
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct EntriesRangeRequest {
45 pub before: Option<u64>,
46 pub limit: u64,
47}
48
49pub fn entries_range(payload: &Map<String, Value>) -> Result<EntriesRangeRequest, ValidationError> {
52 let before = match payload.get("before") {
53 None => None,
54 Some(value) => Some(require_integer(Some(value), "before", 0, MAX_BEFORE)?),
55 };
56 let limit = match payload.get("limit") {
57 None => DEFAULT_ENTRIES_LIMIT,
58 Some(value) => require_integer(Some(value), "limit", 1, MAX_ENTRIES_RANGE_LIMIT as u64)?,
59 };
60 Ok(EntriesRangeRequest { before, limit })
61}
62
63impl EntriesRangeRequest {
64 pub fn resolve(&self, total: u64) -> (u64, u64) {
69 let end = self.before.map_or(total, |before| before.min(total));
70 let start = end.saturating_sub(self.limit);
71 (start, end)
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79pub struct InlineAttachment {
80 pub path: String,
81 pub media_type: String,
82}
83
84pub fn find_inline_attachment<'a>(
88 entries: &'a [SessionEntry],
89 id: &str,
90) -> Option<&'a FileAttachment> {
91 entries
92 .iter()
93 .filter_map(|entry| match entry {
94 SessionEntry::User {
95 attachments: Some(files),
96 ..
97 } => Some(files.as_slice()),
98 _ => None,
99 })
100 .flatten()
101 .find(|file| file.id == id && INLINE_IMAGE_MEDIA_TYPES.contains(&file.media_type.as_str()))
102}