Shared write actions; listing helpers the API can call

7e143f3 · gmorell · 2026-12-03 01:21

12 files +785 -497
Message
{commit_body(@commit)}

Files changed

added src/actions.rs
+556 −0
@@ -0,0 +1,556 @@
1 +//! Writes shared by the web handlers and `/api/v1` (party-slut's
2 +//! `src/actions.rs`): starting a topic, replying, tagging, reacting,
3 +//! bookmarking, watching, and the profile's preferences and avatar.
4 +//!
5 +//! Each one checks what the web always checked — the category is visible to
6 +//! this user (trust level, staff), the account may write (email
7 +//! verification), the topic is open — and does the follow-on work (revision,
8 +//! bump, notifications, trust recompute) in one place, so the app can't get a
9 +//! rule the web doesn't, or miss one. The web handlers turn the result into
10 +//! a redirect or an htmx fragment; the API into JSON.
11 +use axum::http::StatusCode;
12 +use chrono::Utc;
13 +use sea_orm::*;
14 +use tracing::error;
15 +use uuid::Uuid;
16 +
17 +use crate::category_tree::{CategoryTree, Viewer};
18 +use crate::entities::{
19 + bookmarks, categories, category_watches, post_reactions, posts, reaction_types, topic_tags, topics, users,
20 +};
21 +use crate::handlers::focus::ViewMode;
22 +use crate::handlers::forum::{apply_tags, tags_for_topic, TagChip, TopicSort};
23 +use crate::handlers::reactions::{active_reaction_types, reaction_views_for_posts, ReactionView};
24 +use crate::markdown;
25 +use crate::AppState;
26 +
27 +/// Why an action was refused.
28 +#[derive(Debug)]
29 +pub enum ActionError {
30 + /// Doesn't exist, or the user can't see it — deliberately one answer.
31 + NotFound,
32 + /// The account's email address isn't verified and the site requires it.
33 + Unverified,
34 + /// Visible, but not this user's to change (`code` names the rule).
35 + Forbidden { code: &'static str, message: &'static str },
36 + /// The input itself is wrong; the message says how, for a person.
37 + Invalid(String),
38 + Internal(String),
39 +}
40 +
41 +pub type ActionResult<T> = Result<T, ActionError>;
42 +
43 +impl ActionError {
44 + pub fn status(&self) -> StatusCode {
45 + match self {
46 + Self::NotFound => StatusCode::NOT_FOUND,
47 + Self::Unverified | Self::Forbidden { .. } => StatusCode::FORBIDDEN,
48 + Self::Invalid(_) => StatusCode::BAD_REQUEST,
49 + Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
50 + }
51 + }
52 +}
53 +
54 +impl From<DbErr> for ActionError {
55 + fn from(e: DbErr) -> Self {
56 + error!(error = %e, "action failed");
57 + Self::Internal(e.to_string())
58 + }
59 +}
60 +
61 +/// The shared listing helpers answer bare status codes; carry them across.
62 +impl From<StatusCode> for ActionError {
63 + fn from(s: StatusCode) -> Self {
64 + match s {
65 + StatusCode::NOT_FOUND => Self::NotFound,
66 + StatusCode::FORBIDDEN => Self::Forbidden { code: "forbidden", message: "You can't do that." },
67 + StatusCode::BAD_REQUEST => Self::Invalid("That request couldn't be read.".into()),
68 + other => Self::Internal(other.to_string()),
69 + }
70 + }
71 +}
72 +
73 +/// What the web handlers return: the status code alone.
74 +impl From<ActionError> for StatusCode {
75 + fn from(e: ActionError) -> Self {
76 + e.status()
77 + }
78 +}
79 +
80 +/// The read capability of a signed-in user.
81 +pub fn viewer(user: &users::Model) -> Viewer {
82 + Viewer { level: Some(user.trust_level), staff: user.is_staff }
83 +}
84 +
85 +/// [`crate::handlers::may_write`] as an action error.
86 +pub fn require_writer(state: &AppState, user: &users::Model) -> ActionResult<()> {
87 + if crate::handlers::may_write(state, user) {
88 + Ok(())
89 + } else {
90 + Err(ActionError::Unverified)
91 + }
92 +}
93 +
94 +/// A category by slug, if `viewer` may read it.
95 +pub async fn visible_category(
96 + state: &AppState,
97 + viewer: Viewer,
98 + slug: &str,
99 +) -> ActionResult<(categories::Model, CategoryTree)> {
100 + let category = categories::Entity::find()
101 + .filter(categories::Column::Slug.eq(slug))
102 + .one(state.db.as_ref())
103 + .await?
104 + .ok_or(ActionError::NotFound)?;
105 + let tree = CategoryTree::load(state.db.as_ref()).await?;
106 + if !tree.can_view(category.id, viewer) {
107 + return Err(ActionError::NotFound);
108 + }
109 + Ok((category, tree))
110 +}
111 +
112 +/// A topic, if `viewer` may read its category. Deleted topics are included;
113 +/// callers decide what a tombstone means for them.
114 +pub async fn visible_topic(
115 + state: &AppState,
116 + viewer: Viewer,
117 + topic_id: Uuid,
118 +) -> ActionResult<(topics::Model, CategoryTree)> {
119 + let topic = topics::Entity::find_by_id(topic_id)
120 + .one(state.db.as_ref())
121 + .await?
122 + .ok_or(ActionError::NotFound)?;
123 + let tree = CategoryTree::load(state.db.as_ref()).await?;
124 + if !tree.can_view(topic.category_id, viewer) {
125 + return Err(ActionError::NotFound);
126 + }
127 + Ok((topic, tree))
128 +}
129 +
130 +/// A live post in a live topic `viewer` may read.
131 +async fn visible_live_post(state: &AppState, viewer: Viewer, post_id: Uuid) -> ActionResult<posts::Model> {
132 + let post = posts::Entity::find_by_id(post_id)
133 + .one(state.db.as_ref())
134 + .await?
135 + .ok_or(ActionError::NotFound)?;
136 + let (topic, _) = visible_topic(state, viewer, post.topic_id).await?;
137 + if post.deleted_at.is_some() || topic.deleted_at.is_some() {
138 + return Err(ActionError::NotFound);
139 + }
140 + Ok(post)
141 +}
142 +
143 +/// Start a topic in `slug` with its opening post and tags (comma-separated,
144 +/// up to five; minting new ones is trust-gated), and notify the watchers of
145 +/// the category and its ancestors.
146 +pub async fn create_topic(
147 + state: &AppState,
148 + user: &users::Model,
149 + slug: &str,
150 + title: &str,
151 + body: &str,
152 + tags: &str,
153 +) -> ActionResult<topics::Model> {
154 + require_writer(state, user)?;
155 + let (title, body) = (title.trim(), body.trim());
156 + if title.is_empty() {
157 + return Err(ActionError::Invalid("A topic needs a title.".into()));
158 + }
159 + if body.is_empty() {
160 + return Err(ActionError::Invalid("Write something to start the topic with.".into()));
161 + }
162 + let (category, tree) = visible_category(state, viewer(user), slug).await?;
163 +
164 + let now = Utc::now();
165 + let topic = topics::ActiveModel {
166 + id: Set(Uuid::now_v7()),
167 + category_id: Set(category.id),
168 + user_id: Set(user.id),
169 + title: Set(title.to_string()),
170 + is_pinned: Set(false),
171 + is_closed: Set(false),
172 + views: Set(0),
173 + posts_count: Set(1),
174 + created_at: Set(now.into()),
175 + updated_at: Set(now.into()),
176 + bumped_at: Set(now.into()),
177 + deleted_at: Set(None),
178 + deleted_by_id: Set(None),
179 + }
180 + .insert(state.db.as_ref())
181 + .await?;
182 + insert_post(state, user, topic.id, 1, body).await?;
183 +
184 + if !tags.trim().is_empty() {
185 + apply_tags(state, topic.id, tags, user).await?;
186 + }
187 +
188 + let mut watch_ids = tree.ancestors(category.id);
189 + watch_ids.push(category.id);
190 + if let Err(e) =
191 + crate::handlers::notifications::notify_new_topic(state.db.as_ref(), topic.id, user.id, &watch_ids).await
192 + {
193 + error!(error = %e, "notify watchers failed");
194 + }
195 + recompute_trust(state, user).await;
196 + Ok(topic)
197 +}
198 +
199 +/// Reply to a topic: the post, its first revision, the topic bump.
200 +pub async fn reply(state: &AppState, user: &users::Model, topic_id: Uuid, body: &str) -> ActionResult<posts::Model> {
201 + require_writer(state, user)?;
202 + let body = body.trim();
203 + if body.is_empty() {
204 + return Err(ActionError::Invalid("A reply can't be empty.".into()));
205 + }
206 + let (topic, _) = visible_topic(state, viewer(user), topic_id).await?;
207 + if topic.deleted_at.is_some() {
208 + return Err(ActionError::NotFound);
209 + }
210 + if topic.is_closed {
211 + return Err(ActionError::Forbidden { code: "closed", message: "This topic is closed to new replies." });
212 + }
213 + let next_number = topic.posts_count + 1;
214 + let post = insert_post(state, user, topic.id, next_number, body).await?;
215 +
216 + let mut t: topics::ActiveModel = topic.into();
217 + t.posts_count = Set(next_number);
218 + t.bumped_at = Set(post.created_at);
219 + t.update(state.db.as_ref()).await?;
220 + recompute_trust(state, user).await;
221 + Ok(post)
222 +}
223 +
224 +async fn insert_post(
225 + state: &AppState,
226 + user: &users::Model,
227 + topic_id: Uuid,
228 + post_number: i32,
229 + body: &str,
230 +) -> ActionResult<posts::Model> {
231 + let now = Utc::now();
232 + let cooked = markdown::render(body);
233 + let post = posts::ActiveModel {
234 + id: Set(Uuid::now_v7()),
235 + topic_id: Set(topic_id),
236 + user_id: Set(user.id),
237 + post_number: Set(post_number),
238 + raw: Set(body.to_string()),
239 + cooked: Set(cooked.clone()),
240 + created_at: Set(now.into()),
241 + updated_at: Set(now.into()),
242 + edited_at: Set(None),
243 + edit_count: Set(0),
244 + last_editor_id: Set(None),
245 + deleted_at: Set(None),
246 + deleted_by_id: Set(None),
247 + }
248 + .insert(state.db.as_ref())
249 + .await?;
250 + crate::handlers::posts::record_revision(state.db.as_ref(), post.id, 1, user.id, body, &cooked, now.into())
251 + .await?;
252 + Ok(post)
253 +}
254 +
255 +async fn recompute_trust(state: &AppState, user: &users::Model) {
256 + if let Err(e) = crate::trust::recompute(state.db.as_ref(), user).await {
257 + error!(error = %e, "trust recompute failed");
258 + }
259 +}
260 +
261 +/// Whether `user` may change `topic`'s tags: its author or staff, on a live
262 +/// topic, with a verified address.
263 +pub fn can_edit_tags(state: &AppState, user: &users::Model, topic: &topics::Model) -> bool {
264 + topic.deleted_at.is_none() && (user.is_staff || user.id == topic.user_id) && crate::handlers::may_write(state, user)
265 +}
266 +
267 +/// Replace a topic's tags with `tags` (comma-separated). Same rules as at
268 +/// creation. Returns the tags it ended up with.
269 +pub async fn set_topic_tags(
270 + state: &AppState,
271 + user: &users::Model,
272 + topic_id: Uuid,
273 + tags: &str,
274 +) -> ActionResult<Vec<TagChip>> {
275 + require_writer(state, user)?;
276 + let (topic, _) = visible_topic(state, viewer(user), topic_id).await?;
277 + if topic.deleted_at.is_some() {
278 + return Err(ActionError::NotFound);
279 + }
280 + if !(user.is_staff || user.id == topic.user_id) {
281 + return Err(ActionError::Forbidden {
282 + code: "not_author",
283 + message: "Only the topic's author or staff can change its tags.",
284 + });
285 + }
286 + // Drop the links, then apply the list. Tag rows stay (other topics may
287 + // use them; /tags lists zero counts).
288 + topic_tags::Entity::delete_many()
289 + .filter(topic_tags::Column::TopicId.eq(topic.id))
290 + .exec(state.db.as_ref())
291 + .await?;
292 + apply_tags(state, topic.id, tags, user).await?;
293 + let mut t: topics::ActiveModel = topic.clone().into();
294 + t.updated_at = Set(Utc::now().into());
295 + t.update(state.db.as_ref()).await?;
296 + Ok(tags_for_topic(state, topic.id).await?)
297 +}
298 +
299 +/// The key of `user`'s current reaction on a post, if any.
300 +pub async fn current_reaction(state: &AppState, user_id: Uuid, post_id: Uuid) -> ActionResult<Option<String>> {
301 + let Some(r) = post_reactions::Entity::find()
302 + .filter(post_reactions::Column::PostId.eq(post_id))
303 + .filter(post_reactions::Column::UserId.eq(user_id))
304 + .one(state.db.as_ref())
305 + .await?
306 + else {
307 + return Ok(None);
308 + };
309 + Ok(reaction_types::Entity::find_by_id(r.reaction_id).one(state.db.as_ref()).await?.map(|t| t.key))
310 +}
311 +
312 +/// Set `user`'s reaction on a post to `key` (one per user per post; a new
313 +/// key replaces the old one), or clear it with `None`. A brand-new reaction
314 +/// notifies the post's author. Returns the post's reaction bar.
315 +pub async fn set_reaction(
316 + state: &AppState,
317 + user: &users::Model,
318 + post_id: Uuid,
319 + key: Option<&str>,
320 +) -> ActionResult<Vec<ReactionView>> {
321 + require_writer(state, user)?;
322 + let post = visible_live_post(state, viewer(user), post_id).await?;
323 + let existing = post_reactions::Entity::find()
324 + .filter(post_reactions::Column::PostId.eq(post.id))
325 + .filter(post_reactions::Column::UserId.eq(user.id))
326 + .one(state.db.as_ref())
327 + .await?;
328 +
329 + match key {
330 + None => {
331 + if let Some(r) = existing {
332 + post_reactions::Entity::delete_by_id(r.id).exec(state.db.as_ref()).await?;
333 + }
334 + }
335 + Some(key) => {
336 + let rtype = reaction_types::Entity::find()
337 + .filter(reaction_types::Column::Key.eq(key))
338 + .filter(reaction_types::Column::IsActive.eq(true))
339 + .one(state.db.as_ref())
340 + .await?
341 + .ok_or_else(|| ActionError::Invalid(format!("There is no “{key}” reaction.")))?;
342 + match existing {
343 + Some(r) if r.reaction_id == rtype.id => {}
344 + Some(r) => {
345 + let mut am: post_reactions::ActiveModel = r.into();
346 + am.reaction_id = Set(rtype.id);
347 + am.created_at = Set(Utc::now().into());
348 + am.update(state.db.as_ref()).await?;
349 + }
350 + None => {
351 + post_reactions::ActiveModel {
352 + id: Set(Uuid::now_v7()),
353 + post_id: Set(post.id),
354 + user_id: Set(user.id),
355 + reaction_id: Set(rtype.id),
356 + created_at: Set(Utc::now().into()),
357 + }
358 + .insert(state.db.as_ref())
359 + .await?;
360 + if let Err(e) = crate::handlers::notifications::notify_reaction(
361 + state.db.as_ref(),
362 + post.user_id,
363 + user.id,
364 + post.id,
365 + post.topic_id,
366 + )
367 + .await
368 + {
369 + error!(error = %e, "notify reaction failed");
370 + }
371 + }
372 + }
373 + }
374 + }
375 +
376 + let types = active_reaction_types(state.db.as_ref()).await?;
377 + let mut views = reaction_views_for_posts(state.db.as_ref(), &types, &[post.id], Some(user.id)).await?;
378 + Ok(views.remove(&post.id).unwrap_or_default())
379 +}
380 +
381 +/// Bookmark a post, or remove the bookmark. Returns the new state.
382 +pub async fn set_bookmark(state: &AppState, user: &users::Model, post_id: Uuid, on: bool) -> ActionResult<bool> {
383 + require_writer(state, user)?;
384 + let post = visible_live_post(state, viewer(user), post_id).await?;
385 + let existing = bookmarks::Entity::find()
386 + .filter(bookmarks::Column::UserId.eq(user.id))
387 + .filter(bookmarks::Column::PostId.eq(post.id))
388 + .one(state.db.as_ref())
389 + .await?;
390 + match (existing, on) {
391 + (Some(b), false) => {
392 + bookmarks::Entity::delete_by_id(b.id).exec(state.db.as_ref()).await?;
393 + }
394 + (None, true) => {
395 + bookmarks::ActiveModel {
396 + id: Set(Uuid::now_v7()),
397 + user_id: Set(user.id),
398 + post_id: Set(post.id),
399 + created_at: Set(Utc::now().into()),
400 + }
401 + .insert(state.db.as_ref())
402 + .await?;
403 + }
404 + _ => {}
405 + }
406 + Ok(on)
407 +}
408 +
409 +/// Whether `user` has bookmarked `post_id`.
410 +pub async fn is_bookmarked(state: &AppState, user_id: Uuid, post_id: Uuid) -> ActionResult<bool> {
411 + Ok(bookmarks::Entity::find()
412 + .filter(bookmarks::Column::UserId.eq(user_id))
413 + .filter(bookmarks::Column::PostId.eq(post_id))
414 + .count(state.db.as_ref())
415 + .await?
416 + > 0)
417 +}
418 +
419 +/// Whether `user_id` watches `category_id`.
420 +pub async fn is_watching(state: &AppState, user_id: Uuid, category_id: Uuid) -> ActionResult<bool> {
421 + Ok(category_watches::Entity::find()
422 + .filter(category_watches::Column::UserId.eq(user_id))
423 + .filter(category_watches::Column::CategoryId.eq(category_id))
424 + .count(state.db.as_ref())
425 + .await?
426 + > 0)
427 +}
428 +
429 +/// Watch a category (new topics in it and below notify you), or stop.
430 +/// Returns the category and the new state.
431 +pub async fn set_watch(
432 + state: &AppState,
433 + user: &users::Model,
434 + slug: &str,
435 + on: bool,
436 +) -> ActionResult<(categories::Model, bool)> {
437 + let (category, _) = visible_category(state, viewer(user), slug).await?;
438 + let existing = category_watches::Entity::find()
439 + .filter(category_watches::Column::UserId.eq(user.id))
440 + .filter(category_watches::Column::CategoryId.eq(category.id))
441 + .one(state.db.as_ref())
442 + .await?;
443 + match (existing, on) {
444 + (Some(w), false) => {
445 + category_watches::Entity::delete_by_id(w.id).exec(state.db.as_ref()).await?;
446 + }
447 + (None, true) => {
448 + category_watches::ActiveModel {
449 + id: Set(Uuid::now_v7()),
450 + user_id: Set(user.id),
451 + category_id: Set(category.id),
452 + created_at: Set(Utc::now().into()),
453 + }
454 + .insert(state.db.as_ref())
455 + .await?;
456 + }
457 + _ => {}
458 + }
459 + Ok((category, on))
460 +}
461 +
462 +/// The profile's preferences; `None` leaves a field as it is.
463 +#[derive(Debug, Default)]
464 +pub struct Preferences {
465 + pub reaction_notifications: Option<bool>,
466 + pub layout: Option<ViewMode>,
467 + pub sort: Option<TopicSort>,
468 +}
469 +
470 +pub async fn update_preferences(
471 + state: &AppState,
472 + user: &users::Model,
473 + prefs: Preferences,
474 +) -> ActionResult<users::Model> {
475 + let mut am: users::ActiveModel = user.clone().into();
476 + if let Some(on) = prefs.reaction_notifications {
477 + am.reaction_notifications = Set(on);
478 + }
479 + if let Some(mode) = prefs.layout {
480 + am.preferred_view = Set(mode.as_str().to_string());
481 + }
482 + if let Some(sort) = prefs.sort {
483 + am.preferred_sort = Set(sort.as_str().to_string());
484 + }
485 + am.updated_at = Set(Utc::now().into());
486 + Ok(am.update(state.db.as_ref()).await?)
487 +}
488 +
489 +/// Image types an avatar may be.
490 +pub const AVATAR_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
491 +/// Largest avatar accepted.
492 +pub const MAX_AVATAR_BYTES: usize = 5 * 1024 * 1024;
493 +
494 +/// Replace `user`'s avatar.
495 +pub async fn set_avatar(
496 + state: &AppState,
497 + user: &users::Model,
498 + content_type: Option<&str>,
499 + data: Vec<u8>,
500 +) -> ActionResult<users::Model> {
501 + if data.is_empty() {
502 + return Err(ActionError::Invalid("That file is empty.".into()));
503 + }
504 + if data.len() > MAX_AVATAR_BYTES {
505 + return Err(ActionError::Invalid("An avatar can be at most 5 MB.".into()));
506 + }
507 + let content_type = content_type
508 + .filter(|ct| AVATAR_TYPES.contains(ct))
509 + .ok_or_else(|| ActionError::Invalid("An avatar must be a PNG, JPEG, GIF or WebP image.".into()))?;
510 + let mut am: users::ActiveModel = user.clone().into();
511 + am.avatar_data = Set(Some(data));
512 + am.avatar_content_type = Set(Some(content_type.to_string()));
513 + am.updated_at = Set(Utc::now().into());
514 + Ok(am.update(state.db.as_ref()).await?)
515 +}
516 +
517 +/// Back to the generated letter avatar.
518 +pub async fn clear_avatar(state: &AppState, user: &users::Model) -> ActionResult<users::Model> {
519 + let mut am: users::ActiveModel = user.clone().into();
520 + am.avatar_data = Set(None);
521 + am.avatar_content_type = Set(None);
522 + am.updated_at = Set(Utc::now().into());
523 + Ok(am.update(state.db.as_ref()).await?)
524 +}
525 +
526 +/// Mark one of `user_id`'s notifications read. `NotFound` if it isn't theirs.
527 +pub async fn mark_notification_read(
528 + state: &AppState,
529 + user_id: Uuid,
530 + id: Uuid,
531 +) -> ActionResult<crate::entities::notifications::Model> {
532 + use crate::entities::notifications;
533 + let n = notifications::Entity::find_by_id(id)
534 + .filter(notifications::Column::UserId.eq(user_id))
535 + .one(state.db.as_ref())
536 + .await?
537 + .ok_or(ActionError::NotFound)?;
538 + if n.is_read {
539 + return Ok(n);
540 + }
541 + let mut am: notifications::ActiveModel = n.into();
542 + am.is_read = Set(true);
543 + Ok(am.update(state.db.as_ref()).await?)
544 +}
545 +
546 +/// Mark all of `user_id`'s notifications read.
547 +pub async fn mark_all_notifications_read(state: &AppState, user_id: Uuid) -> ActionResult<()> {
548 + use crate::entities::notifications;
549 + notifications::Entity::update_many()
550 + .col_expr(notifications::Column::IsRead, sea_orm::sea_query::Expr::value(true))
551 + .filter(notifications::Column::UserId.eq(user_id))
552 + .filter(notifications::Column::IsRead.eq(false))
553 + .exec(state.db.as_ref())
554 + .await?;
555 + Ok(())
556 +}
modified src/handlers/auth.rs
+10 −10
@@ -374,16 +374,16 @@ pub async fn update_settings(
374 374 user_context: UserContext,
375 375 Form(form): Form<SettingsForm>,
376 376 ) -> Result<impl IntoResponse, StatusCode> {
377 − let mut am: users::ActiveModel = user_context.user.clone().into();
378 − am.reaction_notifications = Set(form.reaction_notifications.is_some());
379 − if let Some(mode) = form.layout.as_deref().and_then(super::focus::ViewMode::parse) {
380 − am.preferred_view = Set(mode.as_str().to_string());
381 − }
382 − am.updated_at = Set(chrono::Utc::now().into());
383 − am.update(state.db.as_ref()).await.map_err(|e| {
384 − error!(error = %e, "update settings failed");
385 − StatusCode::INTERNAL_SERVER_ERROR
386 − })?;
377 + crate::actions::update_preferences(
378 + &state,
379 + &user_context.user,
380 + crate::actions::Preferences {
381 + reaction_notifications: Some(form.reaction_notifications.is_some()),
382 + layout: form.layout.as_deref().and_then(super::focus::ViewMode::parse),
383 + sort: None,
384 + },
385 + )
386 + .await?;
387 387 // The profile is the default from now on: drop any per-page override.
388 388 let mut headers = HeaderMap::new();
389 389 headers.insert(SET_COOKIE, super::focus::clear_session_view_cookie());
modified src/handlers/avatar.rs
+6 −23
@@ -12,8 +12,6 @@ use crate::entities::users;
12 12 use crate::middleware::UserContext;
13 13 use crate::AppState;
14 14
15 −const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
16 −const MAX_AVATAR_BYTES: usize = 5 * 1024 * 1024;
17 15
18 16 /// Serve a user's avatar: their uploaded image if present, otherwise a
19 17 /// generated letter avatar. Always returns an image so templates can use a
@@ -62,21 +60,13 @@ pub async fn upload_avatar(
62 60 if data.is_empty() {
63 61 return Ok(Redirect::to("/profile"));
64 62 }
65 − if data.len() > MAX_AVATAR_BYTES {
63 + if data.len() > crate::actions::MAX_AVATAR_BYTES {
66 64 return Err(StatusCode::PAYLOAD_TOO_LARGE);
67 65 }
68 − let content_type = content_type
69 − .filter(|ct| ALLOWED_TYPES.contains(&ct.as_str()))
70 − .ok_or(StatusCode::UNSUPPORTED_MEDIA_TYPE)?;
71 −
72 − let mut am: users::ActiveModel = user.user.clone().into();
73 − am.avatar_data = Set(Some(data.to_vec()));
74 − am.avatar_content_type = Set(Some(content_type));
75 − am.updated_at = Set(chrono::Utc::now().into());
76 − am.update(state.db.as_ref()).await.map_err(|e| {
77 − error!(error = %e, "save avatar");
78 − StatusCode::INTERNAL_SERVER_ERROR
79 − })?;
66 + if !content_type.as_deref().is_some_and(|ct| crate::actions::AVATAR_TYPES.contains(&ct)) {
67 + return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE);
68 + }
69 + crate::actions::set_avatar(&state, &user.user, content_type.as_deref(), data.to_vec()).await?;
80 70 return Ok(Redirect::to("/profile"));
81 71 }
82 72 Ok(Redirect::to("/profile"))
@@ -87,13 +77,6 @@ pub async fn delete_avatar(
87 77 State(state): State<AppState>,
88 78 user: UserContext,
89 79 ) -> Result<Redirect, StatusCode> {
90 − let mut am: users::ActiveModel = user.user.clone().into();
91 − am.avatar_data = Set(None);
92 − am.avatar_content_type = Set(None);
93 − am.updated_at = Set(chrono::Utc::now().into());
94 − am.update(state.db.as_ref()).await.map_err(|e| {
95 − error!(error = %e, "clear avatar");
96 − StatusCode::INTERNAL_SERVER_ERROR
97 − })?;
80 + crate::actions::clear_avatar(&state, &user.user).await?;
98 81 Ok(Redirect::to("/profile"))
99 82 }
modified src/handlers/bookmarks.rs
+29 −41
@@ -7,7 +7,6 @@ use crate::category_tree::CategoryTree;
7 7 use crate::handlers::focus::{self, ListPage};
8 8 use crate::handlers::forum::viewer_of;
9 9 use axum_htmx::HxRequest;
10 −use chrono::Utc;
11 10 use minijinja::context;
12 11 use sea_orm::*;
13 12 use serde::{Deserialize, Serialize};
@@ -53,42 +52,14 @@ pub async fn toggle_bookmark(
53 52 Query(q): Query<NextQuery>,
54 53 user: UserContext,
55 54 ) -> Result<Response, StatusCode> {
56 − super::require_verified(&state, &user.user)?;
55 + let held = crate::actions::is_bookmarked(&state, user.user.id, id).await?;
56 + let bookmarked = crate::actions::set_bookmark(&state, &user.user, id, !held).await?;
57 57 let post = posts::Entity::find_by_id(id)
58 58 .one(state.db.as_ref())
59 59 .await
60 − .map_err(ise("load post for bookmark"))?
60 + .map_err(ise("reload post"))?
61 61 .ok_or(StatusCode::NOT_FOUND)?;
62 62
63 − let existing = bookmarks::Entity::find()
64 − .filter(bookmarks::Column::UserId.eq(user.user.id))
65 − .filter(bookmarks::Column::PostId.eq(id))
66 − .one(state.db.as_ref())
67 − .await
68 − .map_err(ise("query bookmark"))?;
69 −
70 − let bookmarked = match existing {
71 − Some(b) => {
72 − bookmarks::Entity::delete_by_id(b.id)
73 − .exec(state.db.as_ref())
74 − .await
75 − .map_err(ise("delete bookmark"))?;
76 − false
77 − }
78 − None => {
79 − bookmarks::ActiveModel {
80 − id: Set(Uuid::now_v7()),
81 − user_id: Set(user.user.id),
82 − post_id: Set(id),
83 − created_at: Set(Utc::now().into()),
84 − }
85 − .insert(state.db.as_ref())
86 − .await
87 − .map_err(ise("insert bookmark"))?;
88 − true
89 − }
90 − };
91 −
92 63 if is_htmx {
93 64 let html = render(&state, "forum/_bookmark_button.html", context! {
94 65 post => context! { id => id, bookmarked => bookmarked },
@@ -122,15 +93,18 @@ pub struct BookmarksQuery {
122 93 pub topic: Option<Uuid>,
123 94 }
124 95
125 −/// List the current user's bookmarks, newest first. Only posts in topics the
126 −/// user can (still) see: losing access to a category hides its bookmarks.
127 −pub async fn show_bookmarks(
128 − State(state): State<AppState>,
129 − Query(q): Query<BookmarksQuery>,
130 − headers: HeaderMap,
131 − user: UserContext,
132 −) -> Result<Response, StatusCode> {
133 − let view = focus::view_for(&state, q.view.as_deref(), Some(&user), &headers);
96 +/// A bookmark with its post (None if the post row is gone).
97 +pub(crate) type BookmarkWithPost = (bookmarks::Model, Option<posts::Model>);
98 +/// The topics those bookmarks are in, with their authors.
99 +pub(crate) type BookmarkTopics = HashMap<Uuid, (topics::Model, Option<users::Model>)>;
100 +
101 +/// The user's bookmarks, newest first, keeping only posts in topics they can
102 +/// (still) see: losing access to a category hides its bookmarks. Shared by
103 +/// the page and `/api/v1/bookmarks`.
104 +pub(crate) async fn visible_bookmarks(
105 + state: &AppState,
106 + user: &UserContext,
107 +) -> Result<(Vec<BookmarkWithPost>, BookmarkTopics, CategoryTree), StatusCode> {
134 108 let loaded = bookmarks::Entity::find()
135 109 .filter(bookmarks::Column::UserId.eq(user.user.id))
136 110 .order_by_desc(bookmarks::Column::CreatedAt)
@@ -164,6 +138,20 @@ pub async fn show_bookmarks(
164 138 .filter(|(_, p)| p.as_ref().is_some_and(|p| topic_map.contains_key(&p.topic_id)))
165 139 .collect();
166 140
141 + Ok((loaded, topic_map, tree))
142 +}
143 +
144 +/// List the current user's bookmarks, newest first. Only posts in topics the
145 +/// user can (still) see: losing access to a category hides its bookmarks.
146 +pub async fn show_bookmarks(
147 + State(state): State<AppState>,
148 + Query(q): Query<BookmarksQuery>,
149 + headers: HeaderMap,
150 + user: UserContext,
151 +) -> Result<Response, StatusCode> {
152 + let view = focus::view_for(&state, q.view.as_deref(), Some(&user), &headers);
153 + let (loaded, topic_map, tree) = visible_bookmarks(&state, &user).await?;
154 +
167 155 if view.is_focus() {
168 156 // One tile per live topic, ordered by its newest bookmark; the notes
169 157 // say which posts.
modified src/handlers/focus.rs
+13 −13
@@ -216,16 +216,16 @@ pub(crate) struct UpLink {
216 216 }
217 217
218 218 #[derive(Serialize, Clone)]
219 −struct Avatar {
220 − id: Uuid,
221 − name: String,
222 − has_avatar: bool,
219 +pub(crate) struct Avatar {
220 + pub(crate) id: Uuid,
221 + pub(crate) name: String,
222 + pub(crate) has_avatar: bool,
223 223 }
224 224
225 225 #[derive(Serialize, Clone)]
226 −struct ReactionSum {
227 − emoji: String,
228 − count: usize,
226 +pub(crate) struct ReactionSum {
227 + pub(crate) emoji: String,
228 + pub(crate) count: usize,
229 229 }
230 230
231 231 /// A topic as a tile or a compact square.
@@ -233,14 +233,14 @@ struct ReactionSum {
233 233 pub(crate) struct TopicTile {
234 234 #[serde(flatten)]
235 235 pub(crate) row: TopicRow,
236 − replies: i32,
236 + pub(crate) replies: i32,
237 237 /// The opening poster, then the top repliers.
238 − posters: Vec<Avatar>,
239 − reactions: Vec<ReactionSum>,
238 + pub(crate) posters: Vec<Avatar>,
239 + pub(crate) reactions: Vec<ReactionSum>,
240 240 /// Signed in, never opened, recently active.
241 − is_new: bool,
241 + pub(crate) is_new: bool,
242 242 /// Signed in: posts since they last read it.
243 − unread: i32,
243 + pub(crate) unread: i32,
244 244 /// Extra lines a page adds (bookmarked post, reaction totals,
245 245 /// notifications).
246 246 pub(crate) notes: Vec<String>,
@@ -297,7 +297,7 @@ pub(crate) async fn topic_counts(state: &AppState) -> Result<HashMap<Uuid, u64>,
297 297 Ok(rows.into_iter().map(|(c, n)| (c, n as u64)).collect())
298 298 }
299 299
300 −fn subtree_count(tree: &CategoryTree, vis: &HashSet<Uuid>, counts: &HashMap<Uuid, u64>, id: Uuid) -> u64 {
300 +pub(crate) fn subtree_count(tree: &CategoryTree, vis: &HashSet<Uuid>, counts: &HashMap<Uuid, u64>, id: Uuid) -> u64 {
301 301 tree.self_and_descendants(id)
302 302 .into_iter()
303 303 .filter(|i| vis.contains(i))
modified src/handlers/forum.rs
+65 −217
@@ -17,8 +17,8 @@ const VIEW_WINDOW: Duration = Duration::from_secs(600); // 10 minutes
17 17
18 18 /// Topic-list ordering. Pinned topics always sort first; this controls the
19 19 /// order among the rest (and among pinned).
20 −#[derive(Clone, Copy, PartialEq, Eq)]
21 −pub(crate) enum TopicSort {
20 +#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21 +pub enum TopicSort {
22 22 Latest,
23 23 Top,
24 24 Bottom,
@@ -26,7 +26,7 @@ pub(crate) enum TopicSort {
26 26 }
27 27
28 28 impl TopicSort {
29 − pub(crate) fn parse(s: &str) -> Option<Self> {
29 + pub fn parse(s: &str) -> Option<Self> {
30 30 match s {
31 31 "latest" => Some(Self::Latest),
32 32 "top" => Some(Self::Top),
@@ -36,7 +36,7 @@ impl TopicSort {
36 36 }
37 37 }
38 38
39 − pub(crate) fn as_str(self) -> &'static str {
39 + pub fn as_str(self) -> &'static str {
40 40 match self {
41 41 Self::Latest => "latest",
42 42 Self::Top => "top",
@@ -92,9 +92,7 @@ use crate::category_tree::{color_widget_css, CategoryTree, Viewer};
92 92 use crate::entities::{
93 93 bookmarks, categories, category_watches, posts, tags, topic_reads, topic_tags, topics, users,
94 94 };
95 −use crate::handlers::posts::record_revision;
96 95 use crate::handlers::reactions::{active_reaction_types, reaction_views_for_posts, ReactionView};
97 −use crate::markdown;
98 96 use crate::middleware::UserContext;
99 97 use crate::timeutil::{abs, rel};
100 98 use crate::AppState;
@@ -164,6 +162,13 @@ pub struct TopicRow {
164 162 pub(crate) cat_name: String,
165 163 pub(crate) cat_slug: String,
166 164 pub(crate) tags: Vec<TagChip>,
165 + /// Instants for the API (templates use the strings above).
166 + #[serde(skip)]
167 + pub(crate) created: chrono::DateTime<chrono::FixedOffset>,
168 + #[serde(skip)]
169 + pub(crate) bumped: chrono::DateTime<chrono::FixedOffset>,
170 + #[serde(skip)]
171 + pub(crate) category_id: Uuid,
167 172 }
168 173
169 174 /// Read-capability of an optional viewer.
@@ -174,7 +179,7 @@ pub fn viewer_of(uc: &Option<UserContext>) -> Viewer {
174 179 }
175 180 }
176 181
177 −fn viewer_user(u: &UserContext) -> Viewer {
182 +pub(crate) fn viewer_user(u: &UserContext) -> Viewer {
178 183 Viewer {
179 184 level: Some(u.user.trust_level),
180 185 staff: u.user.is_staff,
@@ -229,7 +234,7 @@ fn tag_slug(s: &str) -> String {
229 234 }
230 235
231 236 /// Tag chips for a single topic.
232 −async fn tags_for_topic(state: &AppState, topic_id: Uuid) -> Result<Vec<TagChip>, StatusCode> {
237 +pub(crate) async fn tags_for_topic(state: &AppState, topic_id: Uuid) -> Result<Vec<TagChip>, StatusCode> {
233 238 Ok(topic_tags::Entity::find()
234 239 .filter(topic_tags::Column::TopicId.eq(topic_id))
235 240 .find_also_related(tags::Entity)
@@ -269,7 +274,7 @@ fn parse_tag_list(raw: &str) -> Vec<(String, String)> {
269 274 /// Attach the tags in `raw` to a topic. Existing tags are reused; brand-new
270 275 /// tags are only minted when `user` meets the trust gate (others are silently
271 276 /// skipped). Does not remove tags already on the topic.
272 −async fn apply_tags(
277 +pub(crate) async fn apply_tags(
273 278 state: &AppState,
274 279 topic_id: Uuid,
275 280 raw: &str,
@@ -360,6 +365,9 @@ pub async fn build_topic_rows(
360 365 };
361 366 TopicRow {
362 367 tags: tag_map.remove(&t.id).unwrap_or_default(),
368 + created: t.created_at,
369 + bumped: t.bumped_at,
370 + category_id: t.category_id,
363 371 id: t.id,
364 372 title: t.title,
365 373 is_pinned: t.is_pinned,
@@ -394,21 +402,25 @@ async fn count_topics_in(state: &AppState, ids: &[Uuid]) -> Result<u64, StatusCo
394 402
395 403 #[derive(Serialize)]
396 404 pub(crate) struct PostRow {
397 − id: Uuid,
398 − post_number: i32,
399 − cooked: String,
400 − created_at: String,
401 − created_at_abs: String,
402 − author: String,
403 − author_id: Uuid,
404 − author_has_avatar: bool,
405 − edited: bool,
406 − deleted: bool,
407 − deleted_by: Option<String>,
408 − can_edit: bool,
409 − can_restore: bool,
410 − bookmarked: bool,
411 − reactions: Vec<ReactionView>,
405 + pub(crate) id: Uuid,
406 + pub(crate) post_number: i32,
407 + pub(crate) cooked: String,
408 + pub(crate) created_at: String,
409 + pub(crate) created_at_abs: String,
410 + pub(crate) author: String,
411 + pub(crate) author_id: Uuid,
412 + pub(crate) author_has_avatar: bool,
413 + pub(crate) edited: bool,
414 + pub(crate) deleted: bool,
415 + pub(crate) deleted_by: Option<String>,
416 + pub(crate) can_edit: bool,
417 + pub(crate) can_restore: bool,
418 + pub(crate) bookmarked: bool,
419 + pub(crate) reactions: Vec<ReactionView>,
420 + #[serde(skip)]
421 + pub(crate) created: chrono::DateTime<chrono::FixedOffset>,
422 + #[serde(skip)]
423 + pub(crate) edited_at: Option<chrono::DateTime<chrono::FixedOffset>>,
412 424 }
413 425
414 426 fn author_name(user: &Option<users::Model>) -> String {
@@ -565,20 +577,7 @@ pub async fn category_show(
565 577 }
566 578
567 579 // Topics from this category AND every VISIBLE descendant roll up here.
568 − let include_ids: Vec<Uuid> = tree
569 − .self_and_descendants(category.id)
570 − .into_iter()
571 − .filter(|i| vis.contains(i))
572 − .collect();
573 −
574 − let mut loaded = topics::Entity::find()
575 − .filter(topics::Column::CategoryId.is_in(include_ids.iter().copied()))
576 − .filter(topics::Column::DeletedAt.is_null())
577 − .find_also_related(users::Entity)
578 − .all(state.db.as_ref())
579 − .await
580 − .map_err(ise("load topics"))?;
581 − sort_topics(&mut loaded, sort);
580 + let loaded = super::focus::category_topics(&state, &tree, &vis, category.id, sort).await?;
582 581 let rows = build_topic_rows(&state, &tree, loaded).await?;
583 582
584 583 let ancestors: Vec<Crumb> = tree
@@ -720,9 +719,8 @@ pub async fn topic_show(
720 719
721 720 let topic_tag_chips = tags_for_topic(&state, topic.id).await?;
722 721 // Tag editing: topic author or staff, on a live topic.
723 − let can_edit_tags = !topic_deleted
724 − && current.is_some_and(|(uid, staff)| staff || uid == topic.user_id)
725 − && user_context.as_ref().is_some_and(|c| super::may_write(&state, &c.user));
722 + let can_edit_tags =
723 + user_context.as_ref().is_some_and(|c| crate::actions::can_edit_tags(&state, &c.user, &topic));
726 724 let may_create_tags = user_context.as_ref().is_some_and(|c| {
727 725 crate::trust::can_create_tags(&c.user, state.config.min_trust_to_create_tag)
728 726 });
@@ -880,6 +878,8 @@ pub(crate) async fn build_post_rows(
880 878 can_restore,
881 879 bookmarked: bookmarked_ids.contains(&p.id),
882 880 reactions: reaction_map.remove(&p.id).unwrap_or_default(),
881 + created: p.created_at,
882 + edited_at: p.edited_at,
883 883 });
884 884 }
885 885
@@ -983,99 +983,24 @@ pub async fn new_topic_form(
983 983 })
984 984 }
985 985
986 −/// Create a topic and its opening post (auth required).
986 +/// Create a topic and its opening post (auth required). The rules and the
987 +/// follow-on work live in [`crate::actions::create_topic`], shared with the API.
987 988 pub async fn create_topic(
988 989 State(state): State<AppState>,
989 990 Path(slug): Path<String>,
990 991 user_context: UserContext,
991 992 Form(form): Form<NewTopicForm>,
992 993 ) -> Result<Redirect, StatusCode> {
993 − super::require_verified(&state, &user_context.user)?;
994 − let title = form.title.trim();
995 − let body = form.body.trim();
996 − if title.is_empty() || body.is_empty() {
997 − return Err(StatusCode::BAD_REQUEST);
998 − }
999 −
1000 − let category = categories::Entity::find()
1001 − .filter(categories::Column::Slug.eq(&slug))
1002 − .one(state.db.as_ref())
1003 − .await
1004 − .map_err(ise("load category"))?
1005 − .ok_or(StatusCode::NOT_FOUND)?;
1006 −
1007 − let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
1008 − if !tree.can_view(category.id, viewer_user(&user_context)) {
1009 − return Err(StatusCode::NOT_FOUND);
1010 − }
1011 −
1012 − let now = Utc::now();
1013 − let topic_id = Uuid::now_v7();
1014 −
1015 − let topic = topics::ActiveModel {
1016 − id: Set(topic_id),
1017 − category_id: Set(category.id),
1018 − user_id: Set(user_context.user.id),
1019 − title: Set(title.to_string()),
1020 − is_pinned: Set(false),
1021 − is_closed: Set(false),
1022 − views: Set(0),
1023 − posts_count: Set(1),
1024 − created_at: Set(now.into()),
1025 − updated_at: Set(now.into()),
1026 − bumped_at: Set(now.into()),
1027 − deleted_at: Set(None),
1028 − deleted_by_id: Set(None),
1029 − };
1030 − topic.insert(state.db.as_ref()).await.map_err(ise("insert topic"))?;
1031 −
1032 − let cooked = markdown::render(body);
1033 − let post_id = Uuid::now_v7();
1034 − let post = posts::ActiveModel {
1035 − id: Set(post_id),
1036 − topic_id: Set(topic_id),
1037 − user_id: Set(user_context.user.id),
1038 − post_number: Set(1),
1039 − raw: Set(body.to_string()),
1040 − cooked: Set(cooked.clone()),
1041 − created_at: Set(now.into()),
1042 − updated_at: Set(now.into()),
1043 − edited_at: Set(None),
1044 − edit_count: Set(0),
1045 − last_editor_id: Set(None),
1046 − deleted_at: Set(None),
1047 − deleted_by_id: Set(None),
1048 − };
1049 − post.insert(state.db.as_ref()).await.map_err(ise("insert opening post"))?;
1050 − record_revision(state.db.as_ref(), post_id, 1, user_context.user.id, body, &cooked, now.into())
1051 − .await
1052 − .map_err(ise("record opening revision"))?;
1053 −
1054 − // Free-form tags (created on demand; up to 5). Minting NEW tags requires a
1055 − // trust level; lower-tier users may still apply existing tags.
1056 − if let Some(raw) = form.tags.as_deref() {
1057 − apply_tags(&state, topic_id, raw, &user_context.user).await?;
1058 − }
1059 −
1060 − // Notify watchers of this category and its ancestors (best-effort).
1061 − let mut watch_ids = tree.ancestors(category.id);
1062 − watch_ids.push(category.id);
1063 − if let Err(e) = crate::handlers::notifications::notify_new_topic(
1064 − state.db.as_ref(),
1065 − topic_id,
1066 − user_context.user.id,
1067 − &watch_ids,
994 + let topic = crate::actions::create_topic(
995 + &state,
996 + &user_context.user,
997 + &slug,
998 + &form.title,
999 + &form.body,
1000 + form.tags.as_deref().unwrap_or(""),
1068 1001 )
1069 − .await
1070 − {
1071 − error!(error = %e, "notify watchers failed");
1072 − }
1073 −
1074 − if let Err(e) = crate::trust::recompute(state.db.as_ref(), &user_context.user).await {
1075 − error!(error = %e, "trust recompute failed");
1076 − }
1077 −
1078 − Ok(Redirect::to(&format!("/t/{topic_id}")))
1002 + .await?;
1003 + Ok(Redirect::to(&format!("/t/{}", topic.id)))
1079 1004 }
1080 1005
1081 1006 #[derive(Debug, Deserialize)]
@@ -1092,61 +1017,9 @@ pub async fn create_post(
1092 1017 user_context: UserContext,
1093 1018 Form(form): Form<ReplyForm>,
1094 1019 ) -> Result<axum::response::Response, StatusCode> {
1095 − super::require_verified(&state, &user_context.user)?;
1096 − let body = form.body.trim();
1097 − if body.is_empty() {
1098 − return Err(StatusCode::BAD_REQUEST);
1099 − }
1100 −
1101 − let topic = topics::Entity::find_by_id(id)
1102 − .one(state.db.as_ref())
1103 − .await
1104 − .map_err(ise("load topic for reply"))?
1105 − .ok_or(StatusCode::NOT_FOUND)?;
1106 −
1107 − {
1108 − let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
1109 − if !tree.can_view(topic.category_id, viewer_user(&user_context)) {
1110 − return Err(StatusCode::NOT_FOUND);
1111 − }
1112 − }
1113 −
1114 − if topic.is_closed {
1115 − return Err(StatusCode::FORBIDDEN);
1116 − }
1117 −
1118 − let next_number = topic.posts_count + 1;
1119 − let now = Utc::now();
1120 − let cooked = markdown::render(body);
1121 −
1122 − let post = posts::ActiveModel {
1123 − id: Set(Uuid::now_v7()),
1124 − topic_id: Set(topic.id),
1125 − user_id: Set(user_context.user.id),
1126 − post_number: Set(next_number),
1127 − raw: Set(body.to_string()),
1128 − cooked: Set(cooked.clone()),
1129 − created_at: Set(now.into()),
1130 − updated_at: Set(now.into()),
1131 − edited_at: Set(None),
1132 − edit_count: Set(0),
1133 − last_editor_id: Set(None),
1134 − deleted_at: Set(None),
1135 − deleted_by_id: Set(None),
1136 − };
1137 − let post = post.insert(state.db.as_ref()).await.map_err(ise("insert reply"))?;
1138 − record_revision(state.db.as_ref(), post.id, 1, user_context.user.id, body, &cooked, now.into())
1139 − .await
1140 − .map_err(ise("record reply revision"))?;
1141 −
1142 − let mut t: topics::ActiveModel = topic.clone().into();
1143 − t.posts_count = Set(next_number);
1144 − t.bumped_at = Set(now.into());
1145 − t.update(state.db.as_ref()).await.map_err(ise("bump topic"))?;
1146 −
1147 − if let Err(e) = crate::trust::recompute(state.db.as_ref(), &user_context.user).await {
1148 − error!(error = %e, "trust recompute failed");
1149 − }
1020 + let post = crate::actions::reply(&state, &user_context.user, id, &form.body).await?;
1021 + let cooked = post.cooked.clone();
1022 + let topic_id = post.topic_id;
1150 1023
1151 1024 if is_htmx {
1152 1025 let row = PostRow {
@@ -1170,6 +1043,8 @@ pub async fn create_post(
1170 1043 .into_iter()
1171 1044 .map(|t| ReactionView { key: t.key, emoji: t.emoji, count: 0, reacted: false })
1172 1045 .collect(),
1046 + created: post.created_at,
1047 + edited_at: None,
1173 1048 };
1174 1049 let html = render(&state, "forum/_post.html", context! {
1175 1050 post => row,
@@ -1177,7 +1052,7 @@ pub async fn create_post(
1177 1052 })?;
1178 1053 Ok(html.into_response())
1179 1054 } else {
1180 − Ok(Redirect::to(&format!("/t/{}", topic.id)).into_response())
1055 + Ok(Redirect::to(&format!("/t/{topic_id}")).into_response())
1181 1056 }
1182 1057 }
1183 1058
@@ -1199,41 +1074,14 @@ pub async fn update_topic_tags(
1199 1074 user_context: UserContext,
1200 1075 Form(form): Form<TopicTagsForm>,
1201 1076 ) -> Result<axum::response::Response, StatusCode> {
1202 − super::require_verified(&state, &user_context.user)?;
1203 − let topic = topics::Entity::find_by_id(id)
1204 − .one(state.db.as_ref())
1205 − .await
1206 − .map_err(ise("load topic for tag edit"))?
1207 − .ok_or(StatusCode::NOT_FOUND)?;
1208 −
1209 − {
1210 − let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
1211 − if !tree.can_view(topic.category_id, viewer_user(&user_context)) {
1212 − return Err(StatusCode::NOT_FOUND);
1213 − }
1214 − }
1215 − if topic.deleted_at.is_some() {
1216 − return Err(StatusCode::NOT_FOUND);
1217 − }
1218 − if !(user_context.user.is_staff || user_context.user.id == topic.user_id) {
1219 − return Err(StatusCode::FORBIDDEN);
1220 − }
1221 −
1222 − // Replace: drop the current links, then apply the submitted list. Tag rows
1223 − // themselves are kept (other topics may use them; /tags lists zero counts).
1224 − topic_tags::Entity::delete_many()
1225 − .filter(topic_tags::Column::TopicId.eq(topic.id))
1226 − .exec(state.db.as_ref())
1227 − .await
1228 − .map_err(ise("clear topic tags"))?;
1229 − apply_tags(&state, topic.id, &form.tags, &user_context.user).await?;
1230 −
1231 − let mut t: topics::ActiveModel = topic.clone().into();
1232 − t.updated_at = Set(Utc::now().into());
1233 − t.update(state.db.as_ref()).await.map_err(ise("touch topic"))?;
1077 + let tag_chips = crate::actions::set_topic_tags(&state, &user_context.user, id, &form.tags).await?;
1234 1078
1235 1079 if is_htmx {
1236 − let tag_chips = tags_for_topic(&state, topic.id).await?;
1080 + let topic = topics::Entity::find_by_id(id)
1081 + .one(state.db.as_ref())
1082 + .await
1083 + .map_err(ise("reload topic"))?
1084 + .ok_or(StatusCode::NOT_FOUND)?;
1237 1085 let may_create_tags =
1238 1086 crate::trust::can_create_tags(&user_context.user, state.config.min_trust_to_create_tag);
1239 1087 let html = render(&state, "forum/_topic_tags.html", context! {
@@ -1245,7 +1093,7 @@ pub async fn update_topic_tags(
1245 1093 })?;
1246 1094 Ok(html.into_response())
1247 1095 } else {
1248 − Ok(Redirect::to(&format!("/t/{}", topic.id)).into_response())
1096 + Ok(Redirect::to(&format!("/t/{id}")).into_response())
1249 1097 }
1250 1098 }
1251 1099
modified src/handlers/notifications.rs
+42 −81
@@ -6,14 +6,13 @@ use axum::{
6 6 use axum_htmx::HxRequest;
7 7 use chrono::Utc;
8 8 use minijinja::context;
9 −use sea_orm::prelude::Expr;
10 9 use sea_orm::*;
11 10 use serde::Serialize;
12 11 use std::collections::{HashMap, HashSet};
13 12 use tracing::error;
14 13 use uuid::Uuid;
15 14
16 −use crate::entities::{categories, category_watches, notifications, topics, users};
15 +use crate::entities::{category_watches, notifications, topics, users};
17 16 use crate::middleware::UserContext;
18 17 use crate::timeutil::{abs, rel};
19 18 use crate::AppState;
@@ -123,41 +122,10 @@ pub async fn toggle_watch(
123 122 HxRequest(is_htmx): HxRequest,
124 123 user: UserContext,
125 124 ) -> Result<Response, StatusCode> {
126 − let category = categories::Entity::find()
127 − .filter(categories::Column::Slug.eq(&slug))
128 − .one(state.db.as_ref())
129 − .await
130 − .map_err(ise("load category for watch"))?
131 − .ok_or(StatusCode::NOT_FOUND)?;
132 −
133 − let existing = category_watches::Entity::find()
134 − .filter(category_watches::Column::UserId.eq(user.user.id))
135 − .filter(category_watches::Column::CategoryId.eq(category.id))
136 − .one(state.db.as_ref())
137 − .await
138 − .map_err(ise("query watch"))?;
139 −
140 − let watching = match existing {
141 − Some(w) => {
142 − category_watches::Entity::delete_by_id(w.id)
143 − .exec(state.db.as_ref())
144 − .await
145 − .map_err(ise("delete watch"))?;
146 − false
147 − }
148 − None => {
149 − category_watches::ActiveModel {
150 − id: Set(Uuid::now_v7()),
151 − user_id: Set(user.user.id),
152 − category_id: Set(category.id),
153 − created_at: Set(Utc::now().into()),
154 − }
155 − .insert(state.db.as_ref())
156 − .await
157 − .map_err(ise("insert watch"))?;
158 − true
159 − }
160 − };
125 + let viewer = crate::actions::viewer(&user.user);
126 + let (category, _) = crate::actions::visible_category(&state, viewer, &slug).await?;
127 + let held = crate::actions::is_watching(&state, user.user.id, category.id).await?;
128 + let (category, watching) = crate::actions::set_watch(&state, &user.user, &slug, !held).await?;
161 129
162 130 if is_htmx {
163 131 let html = render(&state, "forum/_watch_button.html", context! {
@@ -233,36 +201,23 @@ async fn one_notif_row(
233 201 })
234 202 }
235 203
236 −#[derive(Debug, Default, serde::Deserialize)]
237 −pub struct NotificationsQuery {
238 − pub view: Option<String>,
239 − pub topic: Option<Uuid>,
240 −}
241 −
242 −/// The notifications page (the 50 newest). In Focus, grouped by topic: one
243 −/// tile per topic the user can still see, newest first, its notifications as
244 −/// the tile's lines; the rest (no topic, or one now hidden) stay a list.
245 −pub async fn show_notifications(
246 − State(state): State<AppState>,
247 − Query(q): Query<NotificationsQuery>,
248 − headers: HeaderMap,
249 − user: Option<UserContext>,
250 −) -> Result<Response, StatusCode> {
251 − let Some(user) = user else {
252 − return Ok(Redirect::temporary("/login").into_response());
253 − };
254 − let view = crate::handlers::focus::view_for(&state, q.view.as_deref(), Some(&user), &headers);
255 −
204 +/// The user's latest `limit` notifications, minus those about topics in
205 +/// categories they can no longer read (trust lowered, category restricted):
206 +/// their titles would leak. The web page and `/api/v1/notifications` both
207 +/// list through this.
208 +pub(crate) async fn visible_notifications(
209 + state: &AppState,
210 + user: &UserContext,
211 + limit: u64,
212 +) -> Result<Vec<notifications::Model>, StatusCode> {
256 213 let notifs = notifications::Entity::find()
257 214 .filter(notifications::Column::UserId.eq(user.user.id))
258 215 .order_by_desc(notifications::Column::CreatedAt)
259 − .limit(50)
216 + .limit(limit)
260 217 .all(state.db.as_ref())
261 218 .await
262 219 .map_err(ise("load notifications"))?;
263 220
264 − // Drop notifications about topics in categories the user can no longer
265 − // read (trust lowered, category restricted): their titles would leak.
266 221 let notifs = {
267 222 let ids: Vec<Uuid> = notifs.iter().filter_map(|n| n.topic_id).collect();
268 223 let hidden: HashSet<Uuid> = if ids.is_empty() {
@@ -288,6 +243,31 @@ pub async fn show_notifications(
288 243 .collect::<Vec<_>>()
289 244 };
290 245
246 + Ok(notifs)
247 +}
248 +
249 +#[derive(Debug, Default, serde::Deserialize)]
250 +pub struct NotificationsQuery {
251 + pub view: Option<String>,
252 + pub topic: Option<Uuid>,
253 +}
254 +
255 +/// The notifications page (the 50 newest). In Focus, grouped by topic: one
256 +/// tile per topic the user can still see, newest first, its notifications as
257 +/// the tile's lines; the rest (no topic, or one now hidden) stay a list.
258 +pub async fn show_notifications(
259 + State(state): State<AppState>,
260 + Query(q): Query<NotificationsQuery>,
261 + headers: HeaderMap,
262 + user: Option<UserContext>,
263 +) -> Result<Response, StatusCode> {
264 + let Some(user) = user else {
265 + return Ok(Redirect::temporary("/login").into_response());
266 + };
267 + let view = crate::handlers::focus::view_for(&state, q.view.as_deref(), Some(&user), &headers);
268 +
269 + let notifs = visible_notifications(&state, &user, 50).await?;
270 +
291 271 let topic_ids: Vec<Uuid> = notifs.iter().filter_map(|n| n.topic_id).collect();
292 272 let actor_ids: Vec<Uuid> = notifs.iter().filter_map(|n| n.actor_id).collect();
293 273
@@ -413,20 +393,7 @@ pub async fn mark_read(
413 393 Path(id): Path<Uuid>,
414 394 user: UserContext,
415 395 ) -> Result<Html<String>, StatusCode> {
416 − let notif = notifications::Entity::find_by_id(id)
417 − .filter(notifications::Column::UserId.eq(user.user.id))
418 − .one(state.db.as_ref())
419 − .await
420 − .map_err(ise("load notification"))?
421 − .ok_or(StatusCode::NOT_FOUND)?;
422 −
423 − let notif = if notif.is_read {
424 − notif
425 − } else {
426 − let mut am: notifications::ActiveModel = notif.into();
427 − am.is_read = Set(true);
428 − am.update(state.db.as_ref()).await.map_err(ise("mark read"))?
429 − };
396 + let notif = crate::actions::mark_notification_read(&state, user.user.id, id).await?;
430 397
431 398 let row = one_notif_row(state.db.as_ref(), &notif)
432 399 .await
@@ -439,13 +406,7 @@ pub async fn mark_all_read(
439 406 State(state): State<AppState>,
440 407 user: UserContext,
441 408 ) -> Result<Redirect, StatusCode> {
442 − notifications::Entity::update_many()
443 − .col_expr(notifications::Column::IsRead, Expr::value(true))
444 − .filter(notifications::Column::UserId.eq(user.user.id))
445 − .filter(notifications::Column::IsRead.eq(false))
446 − .exec(state.db.as_ref())
447 − .await
448 − .map_err(ise("mark all read"))?;
409 + crate::actions::mark_all_notifications_read(&state, user.user.id).await?;
449 410 Ok(Redirect::to("/notifications"))
450 411 }
451 412
modified src/handlers/reactions.rs
+5 −79
@@ -87,17 +87,6 @@ pub async fn reaction_views_for_posts(
87 87 .collect())
88 88 }
89 89
90 −/// Reaction views for a single post.
91 −async fn reaction_views_for_post(
92 − db: &DatabaseConnection,
93 − types: &[reaction_types::Model],
94 − post_id: Uuid,
95 − current_user: Option<Uuid>,
96 −) -> Result<Vec<ReactionView>, DbErr> {
97 − let map = reaction_views_for_posts(db, types, &[post_id], current_user).await?;
98 − Ok(map.into_values().next().unwrap_or_default())
99 −}
100 −
101 90 fn build_views(
102 91 types: &[reaction_types::Model],
103 92 counts: &HashMap<(Uuid, Uuid), i64>,
@@ -123,79 +112,16 @@ pub async fn toggle_react(
123 112 HxRequest(is_htmx): HxRequest,
124 113 user: UserContext,
125 114 ) -> Result<Response, StatusCode> {
126 − super::require_verified(&state, &user.user)?;
115 + // Clicking the reaction you hold clears it; any other sets it.
116 + let held = crate::actions::current_reaction(&state, user.user.id, id).await?;
117 + let desired = (held.as_deref() != Some(key.as_str())).then_some(key.as_str());
118 + let views = crate::actions::set_reaction(&state, &user.user, id, desired).await?;
127 119 let post = posts::Entity::find_by_id(id)
128 120 .one(state.db.as_ref())
129 121 .await
130 − .map_err(ise("load post for react"))?
122 + .map_err(ise("reload post"))?
131 123 .ok_or(StatusCode::NOT_FOUND)?;
132 124
133 − let rtype = reaction_types::Entity::find()
134 − .filter(reaction_types::Column::Key.eq(&key))
135 − .filter(reaction_types::Column::IsActive.eq(true))
136 − .one(state.db.as_ref())
137 − .await
138 − .map_err(ise("load reaction type"))?
139 − .ok_or(StatusCode::NOT_FOUND)?;
140 −
141 − let existing = post_reactions::Entity::find()
142 − .filter(post_reactions::Column::PostId.eq(id))
143 − .filter(post_reactions::Column::UserId.eq(user.user.id))
144 − .one(state.db.as_ref())
145 − .await
146 − .map_err(ise("query reaction"))?;
147 −
148 − let mut newly_reacted = false;
149 − match existing {
150 − Some(r) if r.reaction_id == rtype.id => {
151 − post_reactions::Entity::delete_by_id(r.id)
152 − .exec(state.db.as_ref())
153 − .await
154 − .map_err(ise("remove reaction"))?;
155 − }
156 − Some(r) => {
157 − let mut am: post_reactions::ActiveModel = r.into();
158 − am.reaction_id = Set(rtype.id);
159 − am.created_at = Set(Utc::now().into());
160 − am.update(state.db.as_ref()).await.map_err(ise("change reaction"))?;
161 − }
162 − None => {
163 − post_reactions::ActiveModel {
164 − id: Set(Uuid::now_v7()),
165 − post_id: Set(id),
166 − user_id: Set(user.user.id),
167 − reaction_id: Set(rtype.id),
168 − created_at: Set(Utc::now().into()),
169 − }
170 − .insert(state.db.as_ref())
171 − .await
172 − .map_err(ise("add reaction"))?;
173 − newly_reacted = true;
174 − }
175 − }
176 −
177 − // Notify the post author on a brand-new reaction (best-effort).
178 − if newly_reacted {
179 − if let Err(e) = crate::handlers::notifications::notify_reaction(
180 − state.db.as_ref(),
181 − post.user_id,
182 − user.user.id,
183 − post.id,
184 − post.topic_id,
185 − )
186 − .await
187 − {
188 − error!(error = %e, "notify reaction failed");
189 − }
190 − }
191 −
192 − let types = active_reaction_types(state.db.as_ref())
193 − .await
194 − .map_err(ise("load reaction types"))?;
195 − let views = reaction_views_for_post(state.db.as_ref(), &types, id, Some(user.user.id))
196 − .await
197 − .map_err(ise("build reaction views"))?;
198 −
199 125 if is_htmx {
200 126 let html = render(&state, "forum/_reactions.html", context! {
201 127 post => context! { id => id, reactions => views },
modified src/handlers/tags.rs
+58 −33
@@ -57,12 +57,12 @@ async fn topics_by_ids(
57 57 }
58 58
59 59 #[derive(Debug, Serialize)]
60 −struct TagAgg {
61 − id: Uuid,
62 − slug: String,
63 − name: String,
60 +pub(crate) struct TagAgg {
61 + pub(crate) id: Uuid,
62 + pub(crate) slug: String,
63 + pub(crate) name: String,
64 64 /// Live topics the viewer can see.
65 − cnt: i64,
65 + pub(crate) cnt: i64,
66 66 /// Those topics, latest activity first.
67 67 #[serde(skip)]
68 68 topics: Vec<Uuid>,
@@ -80,7 +80,7 @@ struct TagLink {
80 80 /// Every tag with the live topics *this viewer* may see. A tag whose topics
81 81 /// are all in categories hidden from the viewer is left out (its name would
82 82 /// leak them); a tag no topic uses yet is listed with 0. Most used first.
83 −async fn visible_tags(state: &AppState, vis: &HashSet<Uuid>) -> Result<Vec<TagAgg>, StatusCode> {
83 +pub(crate) async fn visible_tags(state: &AppState, vis: &HashSet<Uuid>) -> Result<Vec<TagAgg>, StatusCode> {
84 84 let links = TagLink::find_by_statement(Statement::from_string(
85 85 DatabaseBackend::Postgres,
86 86 "SELECT tg.id AS tag_id, tg.slug AS slug, tg.name AS name, t.id AS topic_id, t.category_id AS category_id \
@@ -200,17 +200,16 @@ pub async fn tags_index(
200 200 Ok(view.respond(page))
201 201 }
202 202
203 −/// Topics with a given tag.
204 −pub async fn tag_show(
205 − State(state): State<AppState>,
206 − Path(slug): Path<String>,
207 − Query(q): Query<FocusQuery>,
208 − headers: HeaderMap,
209 − user: Option<UserContext>,
210 −) -> Result<Response, StatusCode> {
211 − let view = focus::view_for(&state, q.view.as_deref(), user.as_ref(), &headers);
203 +/// A tag and its live topics the viewer can see (newest activity first). A
204 +/// tag used only where the viewer can't look doesn't exist for them (as on
205 +/// `/tags`): 404. An unused tag is found, with no topics.
206 +pub(crate) async fn tag_topics(
207 + state: &AppState,
208 + slug: &str,
209 + vis: &HashSet<Uuid>,
210 +) -> Result<(tags::Model, Vec<(topics::Model, Option<users::Model>)>), StatusCode> {
212 211 let tag = tags::Entity::find()
213 − .filter(tags::Column::Slug.eq(&slug))
212 + .filter(tags::Column::Slug.eq(slug))
214 213 .one(state.db.as_ref())
215 214 .await
216 215 .map_err(ise("load tag"))?
@@ -225,9 +224,7 @@ pub async fn tag_show(
225 224 .map(|l| l.topic_id)
226 225 .collect();
227 226
228 − let loaded = topics_by_ids(&state, ids).await?;
229 − let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load tree"))?;
230 − let vis = tree.visible_category_ids(viewer_of(&user));
227 + let loaded = topics_by_ids(state, ids).await?;
231 228 let used = !loaded.is_empty();
232 229 let loaded: Vec<_> = loaded
233 230 .into_iter()
@@ -239,6 +236,22 @@ pub async fn tag_show(
239 236 return Err(StatusCode::NOT_FOUND);
240 237 }
241 238
239 + Ok((tag, loaded))
240 +}
241 +
242 +/// Topics with a given tag.
243 +pub async fn tag_show(
244 + State(state): State<AppState>,
245 + Path(slug): Path<String>,
246 + Query(q): Query<FocusQuery>,
247 + headers: HeaderMap,
248 + user: Option<UserContext>,
249 +) -> Result<Response, StatusCode> {
250 + let view = focus::view_for(&state, q.view.as_deref(), user.as_ref(), &headers);
251 + let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load tree"))?;
252 + let vis = tree.visible_category_ids(viewer_of(&user));
253 + let (tag, loaded) = tag_topics(&state, &slug, &vis).await?;
254 +
242 255 if view.is_focus() {
243 256 let (tiles, reader) =
244 257 focus::tiles_and_reader(&state, &tree, loaded, user.as_ref(), &headers, q.topic).await?;
@@ -288,18 +301,13 @@ struct TopicIdRow {
288 301 id: Uuid,
289 302 }
290 303
291 −/// Full-text-ish search over topic titles, post bodies, and tag names.
292 −pub async fn search(
293 − State(state): State<AppState>,
294 − Query(query): Query<SearchQuery>,
295 − headers: HeaderMap,
296 − user: Option<UserContext>,
297 −) -> Result<Response, StatusCode> {
298 − let view = focus::view_for(&state, query.view.as_deref(), user.as_ref(), &headers);
299 − let q = query.q.unwrap_or_default();
300 − let trimmed = q.trim().to_string();
301 −
302 − let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load tree"))?;
304 +/// Live topics matching `q` (title, post bodies, tag names; at least two
305 +/// characters) that the viewer can see, newest activity first, at most 50.
306 +pub(crate) async fn search_topics(
307 + state: &AppState,
308 + trimmed: &str,
309 + vis: &HashSet<Uuid>,
310 +) -> Result<Vec<(topics::Model, Option<users::Model>)>, StatusCode> {
303 311 let loaded = if trimmed.chars().count() < 2 {
304 312 Vec::new()
305 313 } else {
@@ -324,14 +332,31 @@ pub async fn search(
324 332 .map_err(ise("search query"))?;
325 333
326 334 let ids: Vec<Uuid> = id_rows.into_iter().map(|r| r.id).collect();
327 − let loaded = topics_by_ids(&state, ids).await?;
328 − let vis = tree.visible_category_ids(viewer_of(&user));
335 + let loaded = topics_by_ids(state, ids).await?;
329 336 loaded
330 337 .into_iter()
331 338 .filter(|(t, _)| vis.contains(&t.category_id))
332 339 .collect()
333 340 };
334 341
342 + Ok(loaded)
343 +}
344 +
345 +/// Full-text-ish search over topic titles, post bodies, and tag names.
346 +pub async fn search(
347 + State(state): State<AppState>,
348 + Query(query): Query<SearchQuery>,
349 + headers: HeaderMap,
350 + user: Option<UserContext>,
351 +) -> Result<Response, StatusCode> {
352 + let view = focus::view_for(&state, query.view.as_deref(), user.as_ref(), &headers);
353 + let q = query.q.unwrap_or_default();
354 + let trimmed = q.trim().to_string();
355 +
356 + let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load tree"))?;
357 + let vis = tree.visible_category_ids(viewer_of(&user));
358 + let loaded = search_topics(&state, &trimmed, &vis).await?;
359 +
335 360 if view.is_focus() {
336 361 let (tiles, reader) =
337 362 focus::tiles_and_reader(&state, &tree, loaded, user.as_ref(), &headers, query.topic).await?;
modified src/lib.rs
+1 −0
@@ -1,3 +1,4 @@
1 +pub mod actions;
1 2 pub mod auth;
2 3 pub mod avatar;
3 4 pub mod category_tree;

Parents: 339eba2