1use rusqlite::{params, Connection, Result as SqliteResult};
8use std::collections::{HashMap, HashSet};
9
10pub const MAX_TIMES_SHOWN: i64 = 6;
13
14#[allow(dead_code)]
16#[derive(Debug, Clone)]
17pub struct AlbumSuggestionRecord {
18 pub id: i64,
19 pub kind: String, pub title: String,
21 pub photo_ids_json: String, pub cover_photo_id: Option<i64>,
23 pub fingerprint: String,
24 pub status: String, pub seen_count: i64,
26 pub created_at: String,
27 pub cover_thumbnail_path: Option<String>,
29}
30
31impl AlbumSuggestionRecord {
32 pub fn photo_ids(&self) -> Vec<i64> {
34 serde_json::from_str(&self.photo_ids_json).unwrap_or_default()
35 }
36
37 pub fn photo_count(&self) -> usize {
38 self.photo_ids().len()
39 }
40}
41
42pub struct AlbumSuggestionRepo<'a> {
43 conn: &'a Connection,
44}
45
46impl<'a> AlbumSuggestionRepo<'a> {
47 pub fn new(conn: &'a Connection) -> Self {
48 Self { conn }
49 }
50
51 pub fn insert(
53 &self,
54 kind: &str,
55 title: &str,
56 photo_ids: &[i64],
57 cover_photo_id: Option<i64>,
58 fingerprint: &str,
59 ) -> SqliteResult<i64> {
60 let json = serde_json::to_string(photo_ids).unwrap_or_else(|_| "[]".to_string());
61 self.conn.execute(
62 r#"INSERT INTO album_suggestions
63 (kind, title, photo_ids_json, cover_photo_id, fingerprint, status, seen_count)
64 VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0)"#,
65 params![kind, title, json, cover_photo_id, fingerprint],
66 )?;
67 Ok(self.conn.last_insert_rowid())
68 }
69
70 pub fn get_pending(&self) -> SqliteResult<Vec<AlbumSuggestionRecord>> {
72 let mut stmt = self.conn.prepare(
73 r#"SELECT s.id, s.kind, s.title, s.photo_ids_json, s.cover_photo_id,
74 s.fingerprint, s.status, s.seen_count, s.created_at,
75 pcov.thumbnail_path
76 FROM album_suggestions s
77 LEFT JOIN photos pcov
78 ON pcov.id = s.cover_photo_id
79 AND pcov.is_trashed = FALSE
80 WHERE s.status = 'pending'
81 ORDER BY s.created_at DESC"#,
82 )?;
83 let rows = stmt.query_map([], Self::map_row)?;
84 let mut out = Vec::new();
85 for r in rows {
86 if let Some(record) = self.with_active_photos_only(r?)? {
87 out.push(record);
88 }
89 }
90 Ok(out)
91 }
92
93 pub fn accept(&self, id: i64) -> SqliteResult<()> {
95 let affected = self.conn.execute(
96 "UPDATE album_suggestions SET status = 'accepted' WHERE id = ?1",
97 params![id],
98 )?;
99 if affected == 0 {
100 return Err(rusqlite::Error::QueryReturnedNoRows);
101 }
102 Ok(())
103 }
104
105 pub fn dismiss(&self, id: i64) -> SqliteResult<()> {
107 let affected = self.conn.execute(
108 "UPDATE album_suggestions SET status = 'dismissed' WHERE id = ?1",
109 params![id],
110 )?;
111 if affected == 0 {
112 return Err(rusqlite::Error::QueryReturnedNoRows);
113 }
114 Ok(())
115 }
116
117 pub fn retitle_pending(&self, fingerprint: &str, title: &str) -> SqliteResult<usize> {
120 self.conn.execute(
121 "UPDATE album_suggestions SET title = ?2 WHERE fingerprint = ?1 AND status = 'pending'",
122 rusqlite::params![fingerprint, title],
123 )
124 }
125
126 pub fn get_all_fingerprints(&self) -> SqliteResult<Vec<String>> {
127 let mut stmt = self.conn.prepare(
128 "SELECT fingerprint FROM album_suggestions WHERE status IN ('accepted', 'dismissed', 'pending')",
129 )?;
130 let rows = stmt.query_map([], |row| row.get(0))?;
131 let mut out = Vec::new();
132 for r in rows {
133 out.push(r?);
134 }
135 Ok(out)
136 }
137
138 pub fn photo_sets_by_kind(
140 &self,
141 ) -> SqliteResult<Vec<(String, std::collections::HashSet<i64>)>> {
142 let mut stmt = self
143 .conn
144 .prepare("SELECT kind, photo_ids_json FROM album_suggestions")?;
145 let rows = stmt.query_map([], |row| {
146 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
147 })?;
148 let mut out = Vec::new();
149 for row in rows {
150 let (kind, json) = row?;
151 let ids: Vec<i64> = serde_json::from_str(&json).unwrap_or_default();
152 out.push((kind, ids.into_iter().collect()));
153 }
154 Ok(out)
155 }
156
157 pub fn mark_seen(&self, ids: &[i64]) -> SqliteResult<()> {
159 let mut stmt = self
160 .conn
161 .prepare("UPDATE album_suggestions SET seen_count = seen_count + 1 WHERE id = ?1")?;
162 for id in ids {
163 stmt.execute(params![id])?;
164 }
165 Ok(())
166 }
167
168 pub fn cleanup_old(&self, days: u32) -> SqliteResult<usize> {
171 let affected = self.conn.execute(
172 r#"DELETE FROM album_suggestions
173 WHERE status = 'accepted'
174 AND created_at < datetime('now', ?1)"#,
175 params![format!("-{} days", days)],
176 )?;
177 Ok(affected)
178 }
179
180 fn map_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<AlbumSuggestionRecord> {
181 Ok(AlbumSuggestionRecord {
182 id: row.get(0)?,
183 kind: row.get(1)?,
184 title: row.get(2)?,
185 photo_ids_json: row.get(3)?,
186 cover_photo_id: row.get(4)?,
187 fingerprint: row.get(5)?,
188 status: row.get(6)?,
189 seen_count: row.get(7)?,
190 created_at: row.get(8)?,
191 cover_thumbnail_path: row.get(9)?,
192 })
193 }
194
195 fn with_active_photos_only(
196 &self,
197 mut record: AlbumSuggestionRecord,
198 ) -> SqliteResult<Option<AlbumSuggestionRecord>> {
199 let ids = record.photo_ids();
200 if ids.is_empty() {
201 return Ok(None);
202 }
203 let active = self.active_photo_rows(&ids)?;
204 if active.is_empty() {
205 return Ok(None);
206 }
207 let active_set: HashSet<i64> = active.iter().map(|p| p.id).collect();
208 let active_by_id: HashMap<i64, ActivePhoto> =
209 active.into_iter().map(|p| (p.id, p)).collect();
210 let filtered: Vec<i64> = ids
211 .into_iter()
212 .filter(|id| active_set.contains(id))
213 .collect();
214 record.photo_ids_json = serde_json::to_string(&filtered).unwrap_or_else(|_| "[]".into());
215 let cover_is_active = record
216 .cover_photo_id
217 .map(|id| active_set.contains(&id))
218 .unwrap_or(false);
219 let cover_is_renderable = record
220 .cover_photo_id
221 .and_then(|id| active_by_id.get(&id))
222 .map(|p| p.media_type == "photo" || p.thumbnail_path.is_some())
223 .unwrap_or(false);
224 if !cover_is_active || !cover_is_renderable {
225 record.cover_photo_id = filtered
226 .iter()
227 .copied()
228 .find(|id| {
229 active_by_id
230 .get(id)
231 .map(|p| p.media_type == "photo")
232 .unwrap_or(false)
233 })
234 .or_else(|| {
235 filtered.iter().copied().find(|id| {
236 active_by_id
237 .get(id)
238 .and_then(|p| p.thumbnail_path.as_ref())
239 .is_some()
240 })
241 })
242 .or_else(|| filtered.first().copied());
243 }
244 record.cover_thumbnail_path = record
245 .cover_photo_id
246 .and_then(|id| active_by_id.get(&id))
247 .and_then(|p| p.thumbnail_path.clone());
248 let cover = record.cover_photo_id.and_then(|id| active_by_id.get(&id));
249 let has_renderable_cover = cover
250 .map(|p| p.media_type == "photo" || p.thumbnail_path.is_some())
251 .unwrap_or(false);
252 if has_renderable_cover {
253 Ok(Some(record))
254 } else {
255 Ok(None)
256 }
257 }
258
259 fn active_photo_rows(&self, ids: &[i64]) -> SqliteResult<Vec<ActivePhoto>> {
260 let mut out = Vec::new();
261 for chunk in ids.chunks(900) {
262 let placeholders = (0..chunk.len()).map(|_| "?").collect::<Vec<_>>().join(",");
263 let sql = format!(
264 "SELECT id, media_type, thumbnail_path FROM photos WHERE is_trashed = FALSE AND id IN ({})",
265 placeholders
266 );
267 let mut stmt = self.conn.prepare(&sql)?;
268 let rows =
269 stmt.query_map(rusqlite::params_from_iter(chunk.iter().copied()), |row| {
270 Ok(ActivePhoto {
271 id: row.get(0)?,
272 media_type: row.get(1)?,
273 thumbnail_path: row.get(2)?,
274 })
275 })?;
276 for row in rows {
277 out.push(row?);
278 }
279 }
280 Ok(out)
281 }
282}
283
284#[derive(Debug, Clone)]
285struct ActivePhoto {
286 id: i64,
287 media_type: String,
288 thumbnail_path: Option<String>,
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294 use crate::db::create_schema;
295
296 #[test]
297 fn accept_and_dismiss_report_missing_suggestions() {
298 let conn = Connection::open_in_memory().unwrap();
299 create_schema(&conn).unwrap();
300 let repo = AlbumSuggestionRepo::new(&conn);
301
302 assert!(matches!(
303 repo.accept(999),
304 Err(rusqlite::Error::QueryReturnedNoRows)
305 ));
306 assert!(matches!(
307 repo.dismiss(999),
308 Err(rusqlite::Error::QueryReturnedNoRows)
309 ));
310 }
311}