forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'feat-profile-photo' into redesign-two-uis

Browse files at this commit

f09d14aeee1677c406ece39c1e014e4fb0d551f1Ahmet Kaan GümüşParent: 8f2935e87c8829

22 changed files +2730 -582

crates/izlek-core/migrations/0018_photo_in_the_user.sqladded+5 -0
@@ -0,0 +1,5 @@
1+-- A profile picture lives in the database as bytes, the way an attachment
2+-- lives in its file (0010): no filesystem path survives a backup or a move.
3+-- `photo_path` (0001) never carried a value and is left behind, dead.
4+ALTER TABLE user ADD COLUMN photo BLOB;
5+ALTER TABLE user ADD COLUMN photo_mime TEXT;
crates/izlek-core/src/board.rsmodified+1 -1
@@ -76,7 +76,7 @@ pub enum Moved {
76 pub struct Person {76 pub struct Person {
77 pub id: String,77 pub id: String,
78 pub display_name: String,78 pub display_name: String,
79- pub photo_path: Option<String>,79+ pub has_photo: bool,
80 }80 }
81 81
82 impl Person {82 impl Person {
crates/izlek-core/src/store/mod.rsmodified+10 -7
@@ -137,7 +137,7 @@ pub struct User {
137 pub display_name: String,137 pub display_name: String,
138 pub role: Role,138 pub role: Role,
139 pub password_hash: Option<String>,139 pub password_hash: Option<String>,
140- pub photo_path: Option<String>,140+ pub has_photo: bool,
141 pub created_at: OffsetDateTime,141 pub created_at: OffsetDateTime,
142 pub last_signed_in_at: Option<OffsetDateTime>,142 pub last_signed_in_at: Option<OffsetDateTime>,
143 /// Who made this account. Null for the first account, which nobody143 /// Who made this account. Null for the first account, which nobody
@@ -578,12 +578,15 @@ pub trait Store: BoardReads + DetailReads + 'static {
578 578
579 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>;579 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>;
580 580
581- async fn set_profile(581+ async fn set_profile(&self, user_id: &str, display_name: &str) -> Result<()>;
582- &self,582+
583- user_id: &str,583+ /// Stores the profile photo's bytes and mime type, replacing any previous one.
584- display_name: &str,584+ async fn set_photo(&self, user_id: &str, bytes: &[u8], mime: &str) -> Result<()>;
585- photo_path: Option<&str>,585+
586- ) -> Result<()>;586+ async fn clear_photo(&self, user_id: &str) -> Result<()>;
587+
588+ /// The photo's bytes and mime type, or `None` when none is set.
589+ async fn photo(&self, user_id: &str) -> Result<Option<(Vec<u8>, String)>>;
587 590
588 /// Changes the sign-in address. Refuses with [`StoreError::Conflict`] if591 /// Changes the sign-in address. Refuses with [`StoreError::Conflict`] if
589 /// another account in the same workspace already holds it — the same592 /// another account in the same workspace already holds it — the same
crates/izlek-core/src/store/turso_store.rsmodified+67 -25
@@ -10,7 +10,7 @@ use rand::Rng;
10 use time::OffsetDateTime;10 use time::OffsetDateTime;
11 use time::format_description::well_known::Rfc3339;11 use time::format_description::well_known::Rfc3339;
12 use turso::transaction::TransactionBehavior;12 use turso::transaction::TransactionBehavior;
13-use turso::{Builder, Connection, Row, Value, params};13+use turso::{Builder, Connection, Row, params};
14 use ulid::Ulid;14 use ulid::Ulid;
15 15
16 use super::secret;16 use super::secret;
@@ -70,6 +70,7 @@ const MIGRATIONS: &[(i64, &str)] = &[
70 include_str!("../../migrations/0016_display_preferences.sql"),70 include_str!("../../migrations/0016_display_preferences.sql"),
71 ),71 ),
72 (17, include_str!("../../migrations/0017_ui_preference.sql")),72 (17, include_str!("../../migrations/0017_ui_preference.sql")),
73+ (18, include_str!("../../migrations/0018_photo_in_the_user.sql")),
73 ];74 ];
74 75
75 /// The board a fresh workspace gets, and its columns. `Done` is the column76 /// The board a fresh workspace gets, and its columns. `Done` is the column
@@ -577,7 +578,7 @@ fn user_from(row: &Row) -> Result<User> {
577 display_name: text(row, 3)?,578 display_name: text(row, 3)?,
578 role: Role::parse(&text(row, 4)?).ok_or_else(|| StoreError::Corrupt("role".into()))?,579 role: Role::parse(&text(row, 4)?).ok_or_else(|| StoreError::Corrupt("role".into()))?,
579 password_hash: opt_text(row, 5)?,580 password_hash: opt_text(row, 5)?,
580- photo_path: opt_text(row, 6)?,581+ has_photo: row.get::<i64>(6).map_err(backend)? != 0,
581 created_at: parse_stamp(&text(row, 7)?)?,582 created_at: parse_stamp(&text(row, 7)?)?,
582 last_signed_in_at: opt_stamp(row, 8)?,583 last_signed_in_at: opt_stamp(row, 8)?,
583 invited_by: opt_text(row, 9)?,584 invited_by: opt_text(row, 9)?,
@@ -589,7 +590,7 @@ fn user_from(row: &Row) -> Result<User> {
589 }590 }
590 591
591 const USER_COLUMNS: &str = "id, workspace_id, email, display_name, role, password_hash, \592 const USER_COLUMNS: &str = "id, workspace_id, email, display_name, role, password_hash, \
592- photo_path, created_at, last_signed_in_at, invited_by, timezone, theme, language, ui";593+ (photo IS NOT NULL), created_at, last_signed_in_at, invited_by, timezone, theme, language, ui";
593 594
594 fn signin_link_from(row: &Row) -> Result<SigninLink> {595 fn signin_link_from(row: &Row) -> Result<SigninLink> {
595 Ok(SigninLink {596 Ok(SigninLink {
@@ -943,21 +944,28 @@ impl Store for TursoStore {
943 }944 }
944 }945 }
945 946
946- async fn set_profile(947+ async fn set_profile(&self, user_id: &str, display_name: &str) -> Result<()> {
947- &self,948+ let conn = self.conn.lock().await;
948- user_id: &str,949+ let n = conn
949- display_name: &str,950+ .execute(
950- photo_path: Option<&str>,951+ "UPDATE user SET display_name = ?1 WHERE id = ?2",
951- ) -> Result<()> {952+ params![display_name, user_id],
953+ )
954+ .await
955+ .map_err(backend)?;
956+ if n == 0 {
957+ Err(StoreError::NotFound)
958+ } else {
959+ Ok(())
960+ }
961+ }
962+
963+ async fn set_photo(&self, user_id: &str, bytes: &[u8], mime: &str) -> Result<()> {
952 let conn = self.conn.lock().await;964 let conn = self.conn.lock().await;
953- let photo = match photo_path {
954- Some(p) => Value::from(p.to_string()),
955- None => Value::Null,
956- };
957 let n = conn965 let n = conn
958 .execute(966 .execute(
959- "UPDATE user SET display_name = ?1, photo_path = ?2 WHERE id = ?3",967+ "UPDATE user SET photo = ?1, photo_mime = ?2 WHERE id = ?3",
960- params![display_name, photo, user_id],968+ params![bytes, mime, user_id],
961 )969 )
962 .await970 .await
963 .map_err(backend)?;971 .map_err(backend)?;
@@ -968,6 +976,40 @@ impl Store for TursoStore {
968 }976 }
969 }977 }
970 978
979+ async fn clear_photo(&self, user_id: &str) -> Result<()> {
980+ let conn = self.conn.lock().await;
981+ let n = conn
982+ .execute(
983+ "UPDATE user SET photo = NULL, photo_mime = NULL WHERE id = ?1",
984+ params![user_id],
985+ )
986+ .await
987+ .map_err(backend)?;
988+ if n == 0 {
989+ Err(StoreError::NotFound)
990+ } else {
991+ Ok(())
992+ }
993+ }
994+
995+ async fn photo(&self, user_id: &str) -> Result<Option<(Vec<u8>, String)>> {
996+ let conn = self.conn.lock().await;
997+ let mut rows = conn
998+ .query(
999+ "SELECT photo, photo_mime FROM user WHERE id = ?1",
1000+ params![user_id],
1001+ )
1002+ .await
1003+ .map_err(backend)?;
1004+ match rows.next().await.map_err(backend)? {
1005+ Some(row) => match row.get::<Option<Vec<u8>>>(0).map_err(backend)? {
1006+ Some(bytes) => Ok(Some((bytes, text(&row, 1)?))),
1007+ None => Ok(None),
1008+ },
1009+ None => Ok(None),
1010+ }
1011+ }
1012+
971 async fn set_email(&self, user_id: &str, workspace_id: &str, email: &str) -> Result<()> {1013 async fn set_email(&self, user_id: &str, workspace_id: &str, email: &str) -> Result<()> {
972 let email = fold_email(email);1014 let email = fold_email(email);
973 if let Some(existing) = self.user_by_email(workspace_id, &email).await?1015 if let Some(existing) = self.user_by_email(workspace_id, &email).await?
@@ -2800,7 +2842,7 @@ impl DetailReads for TursoStore {
2800 let conn = self.conn.lock().await;2842 let conn = self.conn.lock().await;
2801 let mut rows = conn2843 let mut rows = conn
2802 .query(2844 .query(
2803- "SELECT u.id, u.display_name, u.photo_path FROM task_assignee a \2845+ "SELECT u.id, u.display_name, (u.photo IS NOT NULL) FROM task_assignee a \
2804 JOIN user u ON u.id = a.user_id \2846 JOIN user u ON u.id = a.user_id \
2805 WHERE a.task_id = ?1 ORDER BY u.display_name",2847 WHERE a.task_id = ?1 ORDER BY u.display_name",
2806 params![task_id],2848 params![task_id],
@@ -2812,7 +2854,7 @@ impl DetailReads for TursoStore {
2812 out.push(Person {2854 out.push(Person {
2813 id: text(&row, 0)?,2855 id: text(&row, 0)?,
2814 display_name: text(&row, 1)?,2856 display_name: text(&row, 1)?,
2815- photo_path: opt_text(&row, 2)?,2857+ has_photo: row.get::<i64>(2).map_err(backend)? != 0,
2816 });2858 });
2817 }2859 }
2818 Ok(out)2860 Ok(out)
@@ -2824,7 +2866,7 @@ impl DetailReads for TursoStore {
2824 // so neither leaves the server for this screen.2866 // so neither leaves the server for this screen.
2825 let mut rows = conn2867 let mut rows = conn
2826 .query(2868 .query(
2827- "SELECT id, display_name, photo_path FROM user \2869+ "SELECT id, display_name, (photo IS NOT NULL) FROM user \
2828 WHERE workspace_id = ?1 AND role <> ?2 ORDER BY display_name",2870 WHERE workspace_id = ?1 AND role <> ?2 ORDER BY display_name",
2829 params![workspace_id, Role::Viewer.as_str()],2871 params![workspace_id, Role::Viewer.as_str()],
2830 )2872 )
@@ -2835,7 +2877,7 @@ impl DetailReads for TursoStore {
2835 out.push(Person {2877 out.push(Person {
2836 id: text(&row, 0)?,2878 id: text(&row, 0)?,
2837 display_name: text(&row, 1)?,2879 display_name: text(&row, 1)?,
2838- photo_path: opt_text(&row, 2)?,2880+ has_photo: row.get::<i64>(2).map_err(backend)? != 0,
2839 });2881 });
2840 }2882 }
2841 Ok(out)2883 Ok(out)
@@ -2883,7 +2925,7 @@ impl DetailReads for TursoStore {
2883 let conn = self.conn.lock().await;2925 let conn = self.conn.lock().await;
2884 let mut rows = conn2926 let mut rows = conn
2885 .query(2927 .query(
2886- "SELECT c.id, c.body, c.created_at, u.id, u.display_name, u.photo_path \2928+ "SELECT c.id, c.body, c.created_at, u.id, u.display_name, (u.photo IS NOT NULL) \
2887 FROM comment c JOIN user u ON u.id = c.author_id \2929 FROM comment c JOIN user u ON u.id = c.author_id \
2888 WHERE c.task_id = ?1 ORDER BY c.created_at, c.rowid",2930 WHERE c.task_id = ?1 ORDER BY c.created_at, c.rowid",
2889 params![task_id],2931 params![task_id],
@@ -2899,7 +2941,7 @@ impl DetailReads for TursoStore {
2899 author: Person {2941 author: Person {
2900 id: text(&row, 3)?,2942 id: text(&row, 3)?,
2901 display_name: text(&row, 4)?,2943 display_name: text(&row, 4)?,
2902- photo_path: opt_text(&row, 5)?,2944+ has_photo: row.get::<i64>(5).map_err(backend)? != 0,
2903 },2945 },
2904 });2946 });
2905 }2947 }
@@ -2939,7 +2981,7 @@ impl DetailReads for TursoStore {
2939 let mut rows = conn2981 let mut rows = conn
2940 .query(2982 .query(
2941 "SELECT a.id, a.kind, a.detail, a.created_at, u.id, u.display_name, \2983 "SELECT a.id, a.kind, a.detail, a.created_at, u.id, u.display_name, \
2942- u.photo_path \2984+ (u.photo IS NOT NULL) \
2943 FROM activity a LEFT JOIN user u ON u.id = a.actor_id \2985 FROM activity a LEFT JOIN user u ON u.id = a.actor_id \
2944 WHERE a.task_id = ?1 ORDER BY a.created_at, a.rowid",2986 WHERE a.task_id = ?1 ORDER BY a.created_at, a.rowid",
2945 params![task_id],2987 params![task_id],
@@ -2952,7 +2994,7 @@ impl DetailReads for TursoStore {
2952 Some(id) => Some(Person {2994 Some(id) => Some(Person {
2953 id,2995 id,
2954 display_name: text(&row, 5)?,2996 display_name: text(&row, 5)?,
2955- photo_path: opt_text(&row, 6)?,2997+ has_photo: row.get::<i64>(6).map_err(backend)? != 0,
2956 }),2998 }),
2957 None => None,2999 None => None,
2958 };3000 };
@@ -3039,7 +3081,7 @@ impl BoardReads for TursoStore {
3039 let conn = self.conn.lock().await;3081 let conn = self.conn.lock().await;
3040 let mut rows = conn3082 let mut rows = conn
3041 .query(3083 .query(
3042- "SELECT a.task_id, u.id, u.display_name, u.photo_path \3084+ "SELECT a.task_id, u.id, u.display_name, (u.photo IS NOT NULL) \
3043 FROM task_assignee a \3085 FROM task_assignee a \
3044 JOIN task t ON t.id = a.task_id \3086 JOIN task t ON t.id = a.task_id \
3045 JOIN user u ON u.id = a.user_id \3087 JOIN user u ON u.id = a.user_id \
@@ -3056,7 +3098,7 @@ impl BoardReads for TursoStore {
3056 Person {3098 Person {
3057 id: text(&row, 1)?,3099 id: text(&row, 1)?,
3058 display_name: text(&row, 2)?,3100 display_name: text(&row, 2)?,
3059- photo_path: opt_text(&row, 3)?,3101+ has_photo: row.get::<i64>(3).map_err(backend)? != 0,
3060 },3102 },
3061 ));3103 ));
3062 }3104 }
crates/izlek-core/tests/store.rsmodified+18 -21
@@ -236,14 +236,14 @@ async fn migrations_apply_once_and_survive_reopen() {
236 let path = dir.join("izlek.db").to_string_lossy().into_owned();236 let path = dir.join("izlek.db").to_string_lossy().into_owned();
237 237
238 let first = TursoStore::open(&path).await.unwrap();238 let first = TursoStore::open(&path).await.unwrap();
239- assert_eq!(first.schema_version().await.unwrap(), 17);239+ assert_eq!(first.schema_version().await.unwrap(), 18);
240 claim(&first).await;240 claim(&first).await;
241 drop(first);241 drop(first);
242 242
243 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and243 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
244 // must not lose what the first open wrote.244 // must not lose what the first open wrote.
245 let second = TursoStore::open(&path).await.unwrap();245 let second = TursoStore::open(&path).await.unwrap();
246- assert_eq!(second.schema_version().await.unwrap(), 17);246+ assert_eq!(second.schema_version().await.unwrap(), 18);
247 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");247 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");
248 drop(second);248 drop(second);
249 let _ = std::fs::remove_dir_all(&dir);249 let _ = std::fs::remove_dir_all(&dir);
@@ -260,7 +260,7 @@ async fn migration_0013_rebuilds_mail_rule_without_losing_its_ledger() {
260 a_pre_0013_store_with_a_rule_send_and_decision().await;260 a_pre_0013_store_with_a_rule_send_and_decision().await;
261 261
262 let store = TursoStore::open(path.to_str().unwrap()).await.unwrap();262 let store = TursoStore::open(path.to_str().unwrap()).await.unwrap();
263- assert_eq!(store.schema_version().await.unwrap(), 17);263+ assert_eq!(store.schema_version().await.unwrap(), 18);
264 assert_eq!(store.board(&workspace).await.unwrap().unwrap().id, board);264 assert_eq!(store.board(&workspace).await.unwrap().unwrap().id, board);
265 265
266 let rules = store.mail_rules(&board).await.unwrap();266 let rules = store.mail_rules(&board).await.unwrap();
@@ -780,7 +780,12 @@ async fn profile_and_role_updates_stick() {
780 780
781 scratch781 scratch
782 .store782 .store
783- .set_profile(&user.id, "Grace H.", Some("photos/grace.png"))783+ .set_profile(&user.id, "Grace H.")
784+ .await
785+ .unwrap();
786+ scratch
787+ .store
788+ .set_photo(&user.id, b"grace-bytes", "image/png")
784 .await789 .await
785 .unwrap();790 .unwrap();
786 scratch791 scratch
@@ -791,9 +796,12 @@ async fn profile_and_role_updates_stick() {
791 let at = OffsetDateTime::now_utc();796 let at = OffsetDateTime::now_utc();
792 scratch.store.mark_signed_in(&user.id, at).await.unwrap();797 scratch.store.mark_signed_in(&user.id, at).await.unwrap();
793 798
799+ let photo = scratch.store.photo(&user.id).await.unwrap().unwrap();
800+ assert_eq!(photo.0, b"grace-bytes".to_vec());
801+ assert_eq!(photo.1, "image/png");
794 let user = scratch.store.user(&user.id).await.unwrap().unwrap();802 let user = scratch.store.user(&user.id).await.unwrap().unwrap();
795 assert_eq!(user.display_name, "Grace H.");803 assert_eq!(user.display_name, "Grace H.");
796- assert_eq!(user.photo_path.as_deref(), Some("photos/grace.png"));804+ assert!(user.has_photo);
797 assert_eq!(user.role, Role::Viewer);805 assert_eq!(user.role, Role::Viewer);
798 // Stored as RFC 3339 text, so equality holds to the second.806 // Stored as RFC 3339 text, so equality holds to the second.
799 assert_eq!(807 assert_eq!(
@@ -802,21 +810,10 @@ async fn profile_and_role_updates_stick() {
802 );810 );
803 811
804 // Clearing the photo is a real update, not a no-op.812 // Clearing the photo is a real update, not a no-op.
805- scratch813+ scratch.store.clear_photo(&user.id).await.unwrap();
806- .store814+ let user = scratch.store.user(&user.id).await.unwrap().unwrap();
807- .set_profile(&user.id, "Grace H.", None)815+ assert!(!user.has_photo);
808- .await816+ assert!(scratch.store.photo(&user.id).await.unwrap().is_none());
809- .unwrap();
810- assert!(
811- scratch
812- .store
813- .user(&user.id)
814- .await
815- .unwrap()
816- .unwrap()
817- .photo_path
818- .is_none()
819- );
820 }817 }
821 818
822 #[tokio::test]819 #[tokio::test]
@@ -2292,7 +2289,7 @@ fn initials_fall_back_to_two_letters() {
2292 let person = |name: &str| Person {2289 let person = |name: &str| Person {
2293 id: "u".into(),2290 id: "u".into(),
2294 display_name: name.into(),2291 display_name: name.into(),
2295- photo_path: None,2292+ has_photo: false,
2296 };2293 };
2297 assert_eq!(person("Mel Duarte").initials(), "MD");2294 assert_eq!(person("Mel Duarte").initials(), "MD");
2298 assert_eq!(person("Ada").initials(), "A");2295 assert_eq!(person("Ada").initials(), "A");
crates/izlek-web/src/auth.rsmodified+26 -7
@@ -17,8 +17,8 @@ use topcoat::router::response::{IntoResponse, Response};
17 use topcoat::router::{HeaderName, StatusCode, header, route};17 use topcoat::router::{HeaderName, StatusCode, header, route};
18 18
19 use crate::server::{19 use crate::server::{
20- Refusal, accounts, clear_session_cookie, client_label, mail, presented_session,20+ Refusal, accounts, clear_session_cookie, client_label, mail, presented_session, require_admin,
21- require_admin, require_user, set_session_cookie,21+ require_user, set_session_cookie,
22 };22 };
23 use crate::settings::encode_q;23 use crate::settings::encode_q;
24 24
@@ -100,7 +100,12 @@ struct ClaimWorkspaceForm {
100 #[route(POST "/api/claim_workspace")]100 #[route(POST "/api/claim_workspace")]
101 async fn claim_workspace(cx: &Cx, Form(input): Form<ClaimWorkspaceForm>) -> Redirect {101 async fn claim_workspace(cx: &Cx, Form(input): Form<ClaimWorkspaceForm>) -> Redirect {
102 match accounts(cx)102 match accounts(cx)
103- .claim_workspace(WORKSPACE_NAME, &input.email, &input.display_name, &input.password)103+ .claim_workspace(
104+ WORKSPACE_NAME,
105+ &input.email,
106+ &input.display_name,
107+ &input.password,
108+ )
104 .await109 .await
105 {110 {
106 Ok((_workspace, signed_in)) => {111 Ok((_workspace, signed_in)) => {
@@ -121,7 +126,10 @@ struct SignInForm {
121 /// password yet, or the password is wrong.126 /// password yet, or the password is wrong.
122 #[route(POST "/api/sign_in")]127 #[route(POST "/api/sign_in")]
123 async fn sign_in(cx: &Cx, Form(input): Form<SignInForm>) -> Redirect {128 async fn sign_in(cx: &Cx, Form(input): Form<SignInForm>) -> Redirect {
124- match accounts(cx).sign_in(&input.email, &input.password, &client_label(cx)).await {129+ match accounts(cx)
130+ .sign_in(&input.email, &input.password, &client_label(cx))
131+ .await
132+ {
125 Ok(signed_in) => {133 Ok(signed_in) => {
126 set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME);134 set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME);
127 redirect(cx, None)135 redirect(cx, None)
@@ -161,7 +169,11 @@ async fn redeem_link(cx: &Cx, Form(input): Form<RedeemLinkForm>) -> Redirect {
161 // Redeemed; the referring `/join/{token}` now names a spent169 // Redeemed; the referring `/join/{token}` now names a spent
162 // link, which would show "no longer works" to someone who just170 // link, which would show "no longer works" to someone who just
163 // signed in, so land on the board itself instead.171 // signed in, so land on the board itself instead.
164- Ok((StatusCode::SEE_OTHER, [(header::LOCATION, "/".to_string())], Json(None)))172+ Ok((
173+ StatusCode::SEE_OTHER,
174+ [(header::LOCATION, "/".to_string())],
175+ Json(None),
176+ ))
165 }177 }
166 Err(error) => redirect(cx, Some(error.into())),178 Err(error) => redirect(cx, Some(error.into())),
167 }179 }
@@ -215,7 +227,10 @@ async fn invite_member(cx: &Cx, Form(input): Form<InviteMemberForm>) -> Result<R
215 Ok(admin) => admin,227 Ok(admin) => admin,
216 Err(refusal) => return invite_answer(cx, has_referer, Err(refusal)),228 Err(refusal) => return invite_answer(cx, has_referer, Err(refusal)),
217 };229 };
218- match accounts(cx).invite(&admin, &input.email, &input.display_name, input.role).await {230+ match accounts(cx)
231+ .invite(&admin, &input.email, &input.display_name, input.role)
232+ .await
233+ {
219 Ok(made) => {234 Ok(made) => {
220 mail(cx).after_invite();235 mail(cx).after_invite();
221 invite_answer(cx, has_referer, Ok(made.user.email))236 invite_answer(cx, has_referer, Ok(made.user.email))
@@ -226,7 +241,11 @@ async fn invite_member(cx: &Cx, Form(input): Form<InviteMemberForm>) -> Result<R
226 241
227 /// The address mailed, or the refusal, either as JSON for a caller with242 /// The address mailed, or the refusal, either as JSON for a caller with
228 /// script or a 303 back to Settings for a browser form post.243 /// script or a 303 back to Settings for a browser form post.
229-fn invite_answer(cx: &Cx, has_referer: bool, outcome: std::result::Result<String, Refusal>) -> Result<Response> {244+fn invite_answer(
245+ cx: &Cx,
246+ has_referer: bool,
247+ outcome: std::result::Result<String, Refusal>,
248+) -> Result<Response> {
230 if !has_referer {249 if !has_referer {
231 return Json(outcome).into_response(cx);250 return Json(outcome).into_response(cx);
232 }251 }
crates/izlek-web/src/board.rsmodified+55 -28
@@ -6,7 +6,7 @@
6 //! the server — a drag's only client-side memory is the browser's own drag6 //! the server — a drag's only client-side memory is the browser's own drag
7 //! session (`dataTransfer`), read back by the column that catches the drop.7 //! session (`dataTransfer`), read back by the column that catches the drop.
8 8
9-use izlek_core::board::{DeadlineState, Moved, Person, TaskCard};9+use izlek_core::board::{DeadlineState, Moved, TaskCard};
10 use izlek_core::store::{NewTask, User};10 use izlek_core::store::{NewTask, User};
11 use time::{Date, OffsetDateTime};11 use time::{Date, OffsetDateTime};
12 use topcoat::Result;12 use topcoat::Result;
@@ -50,7 +50,13 @@ async fn move_card_shared(
50 return Ok(Some(Refusal::Forbidden));50 return Ok(Some(Refusal::Forbidden));
51 }51 }
52 match store52 match store
53- .move_task(task_id, from_column_id, to_column_id, &user.id, OffsetDateTime::now_utc())53+ .move_task(
54+ task_id,
55+ from_column_id,
56+ to_column_id,
57+ &user.id,
58+ OffsetDateTime::now_utc(),
59+ )
54 .await60 .await
55 {61 {
56 Ok(Moved::Recorded(transition)) => {62 Ok(Moved::Recorded(transition)) => {
@@ -154,7 +160,15 @@ struct CreateTaskForm {
154 /// fields the procedure below trades over the wire.160 /// fields the procedure below trades over the wire.
155 #[route(POST "/api/create_task")]161 #[route(POST "/api/create_task")]
156 async fn create_task(cx: &Cx, Form(input): Form<CreateTaskForm>) -> Redirect {162 async fn create_task(cx: &Cx, Form(input): Form<CreateTaskForm>) -> Redirect {
157- match create_task_shared(cx, &input.title, &input.column_id, &input.description, &input.deadline).await? {163+ match create_task_shared(
164+ cx,
165+ &input.title,
166+ &input.column_id,
167+ &input.description,
168+ &input.deadline,
169+ )
170+ .await?
171+ {
158 Some(refusal) => redirect_refused(cx, "create_task", refusal),172 Some(refusal) => redirect_refused(cx, "create_task", refusal),
159 // Created; the referring `/?new=1` would reopen a blank new-task173 // Created; the referring `/?new=1` would reopen a blank new-task
160 // modal, so land on the board itself instead.174 // modal, so land on the board itself instead.
@@ -173,7 +187,14 @@ struct MoveCardForm {
173 /// and the drop handler in `card_menu_script` all post here.187 /// and the drop handler in `card_menu_script` all post here.
174 #[route(POST "/api/move_card")]188 #[route(POST "/api/move_card")]
175 async fn move_card(cx: &Cx, Form(input): Form<MoveCardForm>) -> Redirect {189 async fn move_card(cx: &Cx, Form(input): Form<MoveCardForm>) -> Redirect {
176- match move_card_shared(cx, &input.task_id, &input.from_column_id, &input.to_column_id).await? {190+ match move_card_shared(
191+ cx,
192+ &input.task_id,
193+ &input.from_column_id,
194+ &input.to_column_id,
195+ )
196+ .await?
197+ {
177 Some(refusal) => redirect_refused(cx, "move_card", refusal),198 Some(refusal) => redirect_refused(cx, "move_card", refusal),
178 None => redirect(cx),199 None => redirect(cx),
179 }200 }
@@ -232,8 +253,11 @@ async fn board_columns(cx: &Cx, sort: String) -> Result {
232 let today = OffsetDateTime::now_utc().date();253 let today = OffsetDateTime::now_utc().date();
233 let may_write = user.role.can_write_tasks();254 let may_write = user.role.can_write_tasks();
234 255
235- let all_columns: Vec<(String, String)> =256+ let all_columns: Vec<(String, String)> = view_data
236- view_data.columns.iter().map(|column| (column.column.id.clone(), column.column.name.clone())).collect();257+ .columns
258+ .iter()
259+ .map(|column| (column.column.id.clone(), column.column.name.clone()))
260+ .collect();
237 let mut columns = Vec::new();261 let mut columns = Vec::new();
238 for column in view_data.columns {262 for column in view_data.columns {
239 columns.push(render_column(cx, column, today, may_write, &all_columns, lang).await?);263 columns.push(render_column(cx, column, today, may_write, &all_columns, lang).await?);
@@ -260,7 +284,19 @@ async fn render_column(
260 let is_empty = column.cards.is_empty();284 let is_empty = column.cards.is_empty();
261 let mut cards = Vec::new();285 let mut cards = Vec::new();
262 for card in column.cards {286 for card in column.cards {
263- cards.push(render_card(cx, card, today, is_done_column, &column_id, may_write, all_columns, lang).await?);287+ cards.push(
288+ render_card(
289+ cx,
290+ card,
291+ today,
292+ is_done_column,
293+ &column_id,
294+ may_write,
295+ all_columns,
296+ lang,
297+ )
298+ .await?,
299+ );
264 }300 }
265 301
266 view! {302 view! {
@@ -307,15 +343,18 @@ async fn render_card(
307 let comments = card.comment_count;343 let comments = card.comment_count;
308 let mut assignees = Vec::new();344 let mut assignees = Vec::new();
309 for person in card.assignees.iter() {345 for person in card.assignees.iter() {
310- assignees.push(avatar(cx, person, "").await?);346+ assignees.push(crate::layout::avatar(cx, person, "").await?);
311 }347 }
312 let has_assignees = !card.assignees.is_empty();348 let has_assignees = !card.assignees.is_empty();
313 let task_id = card.id.clone();349 let task_id = card.id.clone();
314 let from_column = column_id.to_string();350 let from_column = column_id.to_string();
315 let href = format!("/?task={}", card.id);351 let href = format!("/?task={}", card.id);
316 let menu_id = format!("card-menu-{}", card.id);352 let menu_id = format!("card-menu-{}", card.id);
317- let move_targets: Vec<(String, String)> =353+ let move_targets: Vec<(String, String)> = all_columns
318- all_columns.iter().filter(|(id, _)| id != column_id).cloned().collect();354+ .iter()
355+ .filter(|(id, _)| id != column_id)
356+ .cloned()
357+ .collect();
319 view! {358 view! {
320 cx =>359 cx =>
321 <a class="card" class:card-done=(done_column) href=(href.clone())360 <a class="card" class:card-done=(done_column) href=(href.clone())
@@ -444,21 +483,6 @@ async fn card_menu_script(cx: &Cx) -> Result {
444 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }483 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
445 }484 }
446 485
447-pub(crate) async fn avatar(cx: &Cx, person: &Person, extra: &str) -> Result {
448- let initials = person.initials();
449- let tone = person
450- .id
451- .bytes()
452- .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32))
453- % 5;
454- let class = format!("avatar avatar-tone-{tone} {extra}");
455- let name = person.display_name.clone();
456- view! {
457- cx =>
458- <span class=(class) data-name=(name)>(initials)</span>
459- }
460-}
461-
462 /// Which task, if any, `/` renders the detail modal open on, and the refusal486 /// Which task, if any, `/` renders the detail modal open on, and the refusal
463 /// (if any) a create or move landed back here with. `file` opens the viewer487 /// (if any) a create or move landed back here with. `file` opens the viewer
464 /// over that task's modal, the same nested query-param convention `confirm`488 /// over that task's modal, the same nested query-param convention `confirm`
@@ -502,8 +526,11 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
502 let overdue = view_data.overdue_count(today);526 let overdue = view_data.overdue_count(today);
503 let blocked = view_data.blocked_count();527 let blocked = view_data.blocked_count();
504 let may_write = user.role.can_write_tasks();528 let may_write = user.role.can_write_tasks();
505- let all_columns: Vec<(String, String)> =529+ let all_columns: Vec<(String, String)> = view_data
506- view_data.columns.iter().map(|column| (column.column.id.clone(), column.column.name.clone())).collect();530+ .columns
531+ .iter()
532+ .map(|column| (column.column.id.clone(), column.column.name.clone()))
533+ .collect();
507 let query = query_params::<BoardQuery>(cx)?;534 let query = query_params::<BoardQuery>(cx)?;
508 let open_task = query.task.clone();535 let open_task = query.task.clone();
509 // `?task=X&new=1` together would render both modals at once — two536 // `?task=X&new=1` together would render both modals at once — two
@@ -525,7 +552,7 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
525 </a>552 </a>
526 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Board, lang).await?)553 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Board, lang).await?)
527 <div class="spacer"></div>554 <div class="spacer"></div>
528- (crate::layout::user_menu(cx, &user.display_name, &user.email, user.role, lang).await?)555+ (crate::layout::user_menu(cx, &crate::detail::Me::from(user), lang).await?)
529 </header>556 </header>
530 <div class="filterbar">557 <div class="filterbar">
531 <div class="topbar-divider"></div>558 <div class="topbar-divider"></div>
crates/izlek-web/src/detail.rsmodified+130 -41
@@ -17,7 +17,9 @@
17 //! unchanged.17 //! unchanged.
18 18
19 use izlek_core::board::{DeadlineState, Person};19 use izlek_core::board::{DeadlineState, Person};
20-use izlek_core::detail::{Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in, parse_zone};20+use izlek_core::detail::{
21+ Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in, parse_zone,
22+};
21 use izlek_core::store::{Store, StoreError, User};23 use izlek_core::store::{Store, StoreError, User};
22 use serde::{Deserialize, Serialize};24 use serde::{Deserialize, Serialize};
23 use time::{Date, UtcOffset};25 use time::{Date, UtcOffset};
@@ -49,6 +51,7 @@ pub struct Me {
49 pub email: String,51 pub email: String,
50 pub role: izlek_core::Role,52 pub role: izlek_core::Role,
51 pub language: String,53 pub language: String,
54+ pub has_photo: bool,
52 }55 }
53 56
54 impl From<&User> for Me {57 impl From<&User> for Me {
@@ -59,6 +62,7 @@ impl From<&User> for Me {
59 email: user.email.clone(),62 email: user.email.clone(),
60 role: user.role,63 role: user.role,
61 language: user.language.clone(),64 language: user.language.clone(),
65+ has_photo: user.has_photo,
62 }66 }
63 }67 }
64 }68 }
@@ -124,7 +128,11 @@ mod resolve_direction_tests {
124 /// The task, if this person's workspace is the one holding it. A task in128 /// The task, if this person's workspace is the one holding it. A task in
125 /// another workspace is not found rather than forbidden: the answer says129 /// another workspace is not found rather than forbidden: the answer says
126 /// nothing about whether the id is real.130 /// nothing about whether the id is real.
127-async fn task_of(store: &dyn Store, user: &User, task_id: &str) -> std::result::Result<TaskFacts, Refusal> {131+async fn task_of(
132+ store: &dyn Store,
133+ user: &User,
134+ task_id: &str,
135+) -> std::result::Result<TaskFacts, Refusal> {
128 match store.task(task_id).await {136 match store.task(task_id).await {
129 Ok(Some(facts)) if facts.workspace_id == user.workspace_id => Ok(facts),137 Ok(Some(facts)) if facts.workspace_id == user.workspace_id => Ok(facts),
130 Ok(_) => Err(Refusal::NotFound),138 Ok(_) => Err(Refusal::NotFound),
@@ -136,7 +144,10 @@ async fn task_of(store: &dyn Store, user: &User, task_id: &str) -> std::result::
136 }144 }
137 145
138 /// The writer behind this request and the task they named.146 /// The writer behind this request and the task they named.
139-async fn writer_and_task(cx: &Cx, task_id: &str) -> std::result::Result<(User, TaskFacts), Refusal> {147+async fn writer_and_task(
148+ cx: &Cx,
149+ task_id: &str,
150+) -> std::result::Result<(User, TaskFacts), Refusal> {
140 let user = require_writer(cx).await?;151 let user = require_writer(cx).await?;
141 let store = accounts(cx).store().clone();152 let store = accounts(cx).store().clone();
142 let facts = task_of(store.as_ref(), &user, task_id).await?;153 let facts = task_of(store.as_ref(), &user, task_id).await?;
@@ -157,7 +168,11 @@ fn back_to(cx: &Cx) -> String {
157 }168 }
158 169
159 fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {170 fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
160- Ok((StatusCode::SEE_OTHER, [(header::LOCATION, back_to(cx))], Json(refusal)))171+ Ok((
172+ StatusCode::SEE_OTHER,
173+ [(header::LOCATION, back_to(cx))],
174+ Json(refusal),
175+ ))
161 }176 }
162 177
163 // -- the ten calls --------------------------------------------------------178 // -- the ten calls --------------------------------------------------------
@@ -208,7 +223,10 @@ struct FileIdForm {
208 /// Shared by the route and [`task_modal`], which calls it directly rather223 /// Shared by the route and [`task_modal`], which calls it directly rather
209 /// than going back through its own HTTP endpoint — the same shape `pages.rs`224 /// than going back through its own HTTP endpoint — the same shape `pages.rs`
210 /// reads the store straight through for its own screens.225 /// reads the store straight through for its own screens.
211-async fn load_snapshot(cx: &Cx, task_id: &str) -> Result<std::result::Result<DetailSnapshot, Refusal>> {226+async fn load_snapshot(
227+ cx: &Cx,
228+ task_id: &str,
229+) -> Result<std::result::Result<DetailSnapshot, Refusal>> {
212 use izlek_core::detail::load;230 use izlek_core::detail::load;
213 use time::OffsetDateTime;231 use time::OffsetDateTime;
214 232
@@ -258,7 +276,9 @@ async fn load_snapshot(cx: &Cx, task_id: &str) -> Result<std::result::Result<Det
258 .as_ref()276 .as_ref()
259 .map(|workspace| workspace.allowed_file_types.clone())277 .map(|workspace| workspace.allowed_file_types.clone())
260 .unwrap_or_default();278 .unwrap_or_default();
261- let attachment_limit_mb = workspace.map(|workspace| workspace.attachment_limit_bytes / MB).unwrap_or(0);279+ let attachment_limit_mb = workspace
280+ .map(|workspace| workspace.attachment_limit_bytes / MB)
281+ .unwrap_or(0);
262 282
263 Ok(Ok(DetailSnapshot {283 Ok(Ok(DetailSnapshot {
264 detail,284 detail,
@@ -275,7 +295,10 @@ async fn load_snapshot(cx: &Cx, task_id: &str) -> Result<std::result::Result<Det
275 }295 }
276 296
277 #[route(POST "/api/fetch_task")]297 #[route(POST "/api/fetch_task")]
278-async fn fetch_task(cx: &Cx, Form(input): Form<TaskIdForm>) -> Result<Json<std::result::Result<DetailSnapshot, Refusal>>> {298+async fn fetch_task(
299+ cx: &Cx,
300+ Form(input): Form<TaskIdForm>,
301+) -> Result<Json<std::result::Result<DetailSnapshot, Refusal>>> {
279 Ok(Json(load_snapshot(cx, &input.task_id).await?))302 Ok(Json(load_snapshot(cx, &input.task_id).await?))
280 }303 }
281 304
@@ -318,7 +341,14 @@ async fn save_task(cx: &Cx, Form(input): Form<SaveTaskForm>) -> Redirect {
318 341
319 let store = accounts(cx).store().clone();342 let store = accounts(cx).store().clone();
320 let activity_ids = store343 let activity_ids = store
321- .save_task(&input.task_id, &title, &description, deadline, &user.id, OffsetDateTime::now_utc())344+ .save_task(
345+ &input.task_id,
346+ &title,
347+ &description,
348+ deadline,
349+ &user.id,
350+ OffsetDateTime::now_utc(),
351+ )
322 .await?;352 .await?;
323 for activity_id in activity_ids {353 for activity_id in activity_ids {
324 mail(cx).after_activity(store.clone(), activity_id);354 mail(cx).after_activity(store.clone(), activity_id);
@@ -350,7 +380,13 @@ async fn assign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
350 380
351 store.assign_task(&input.task_id, &person.id).await?;381 store.assign_task(&input.task_id, &person.id).await?;
352 let activity_id = store382 let activity_id = store
353- .record_activity(&input.task_id, Some(&actor.id), &ActivityKind::Assigned, &person.display_name, OffsetDateTime::now_utc())383+ .record_activity(
384+ &input.task_id,
385+ Some(&actor.id),
386+ &ActivityKind::Assigned,
387+ &person.display_name,
388+ OffsetDateTime::now_utc(),
389+ )
354 .await?;390 .await?;
355 mail(cx).after_activity(store, activity_id);391 mail(cx).after_activity(store, activity_id);
356 redirect(cx, None)392 redirect(cx, None)
@@ -375,7 +411,13 @@ async fn unassign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
375 }411 }
376 store.unassign_task(&input.task_id, &person.id).await?;412 store.unassign_task(&input.task_id, &person.id).await?;
377 let activity_id = store413 let activity_id = store
378- .record_activity(&input.task_id, Some(&actor.id), &ActivityKind::Unassigned, &person.display_name, OffsetDateTime::now_utc())414+ .record_activity(
415+ &input.task_id,
416+ Some(&actor.id),
417+ &ActivityKind::Unassigned,
418+ &person.display_name,
419+ OffsetDateTime::now_utc(),
420+ )
379 .await?;421 .await?;
380 mail(cx).after_activity(store, activity_id);422 mail(cx).after_activity(store, activity_id);
381 redirect(cx, None)423 redirect(cx, None)
@@ -407,7 +449,13 @@ async fn link_tasks(cx: &Cx, Form(input): Form<LinkForm>) -> Redirect {
407 Err(error) => return Err(error.into()),449 Err(error) => return Err(error.into()),
408 }450 }
409 let activity_id = store451 let activity_id = store
410- .record_activity(&input.task_id, Some(&actor.id), &ActivityKind::Linked, &other.row.task_key, now)452+ .record_activity(
453+ &input.task_id,
454+ Some(&actor.id),
455+ &ActivityKind::Linked,
456+ &other.row.task_key,
457+ now,
458+ )
411 .await?;459 .await?;
412 mail(cx).after_activity(store, activity_id);460 mail(cx).after_activity(store, activity_id);
413 redirect(cx, None)461 redirect(cx, None)
@@ -434,7 +482,13 @@ async fn unlink_tasks(cx: &Cx, Form(input): Form<LinkForm>) -> Redirect {
434 let now = OffsetDateTime::now_utc();482 let now = OffsetDateTime::now_utc();
435 store.clear_dependency(&blocked, &blocking, now).await?;483 store.clear_dependency(&blocked, &blocking, now).await?;
436 let activity_id = store484 let activity_id = store
437- .record_activity(&input.task_id, Some(&actor.id), &ActivityKind::Unlinked, &other.row.task_key, now)485+ .record_activity(
486+ &input.task_id,
487+ Some(&actor.id),
488+ &ActivityKind::Unlinked,
489+ &other.row.task_key,
490+ now,
491+ )
438 .await?;492 .await?;
439 mail(cx).after_activity(store, activity_id);493 mail(cx).after_activity(store, activity_id);
440 redirect(cx, None)494 redirect(cx, None)
@@ -462,14 +516,19 @@ async fn post_comment(cx: &Cx, Form(input): Form<CommentForm>) -> Redirect {
462 return redirect(cx, Some(Refusal::EmptyComment));516 return redirect(cx, Some(Refusal::EmptyComment));
463 }517 }
464 518
465- let written = store.add_comment(&input.task_id, &user.id, body, OffsetDateTime::now_utc()).await?;519+ let written = store
520+ .add_comment(&input.task_id, &user.id, body, OffsetDateTime::now_utc())
521+ .await?;
466 mail(cx).after_activity(store, written.activity_id);522 mail(cx).after_activity(store, written.activity_id);
467 redirect(cx, None)523 redirect(cx, None)
468 }524 }
469 525
470 /// What a delete would take with it, for the confirmation step. Reads only.526 /// What a delete would take with it, for the confirmation step. Reads only.
471 #[route(POST "/api/what_delete_costs")]527 #[route(POST "/api/what_delete_costs")]
472-async fn what_delete_costs(cx: &Cx, Form(input): Form<TaskIdForm>) -> Result<Json<std::result::Result<DeletionCost, Refusal>>> {528+async fn what_delete_costs(
529+ cx: &Cx,
530+ Form(input): Form<TaskIdForm>,
531+) -> Result<Json<std::result::Result<DeletionCost, Refusal>>> {
473 if let Err(refusal) = writer_and_task(cx, &input.task_id).await {532 if let Err(refusal) = writer_and_task(cx, &input.task_id).await {
474 return Ok(Json(Err(refusal)));533 return Ok(Json(Err(refusal)));
475 }534 }
@@ -491,7 +550,9 @@ async fn delete_task(cx: &Cx, Form(input): Form<TaskIdForm>) -> Redirect {
491 Err(refusal) => return redirect(cx, Some(refusal)),550 Err(refusal) => return redirect(cx, Some(refusal)),
492 };551 };
493 let store = accounts(cx).store().clone();552 let store = accounts(cx).store().clone();
494- let deletion = store.delete_task(&input.task_id, &user.id, OffsetDateTime::now_utc()).await?;553+ let deletion = store
554+ .delete_task(&input.task_id, &user.id, OffsetDateTime::now_utc())
555+ .await?;
495 // A blocker being deleted unblocks whatever was waiting only on it, which556 // A blocker being deleted unblocks whatever was waiting only on it, which
496 // is the same news as the blocker finishing. The freeing is committed;557 // is the same news as the blocker finishing. The freeing is committed;
497 // the send is a separate step, off the request.558 // the send is a separate step, off the request.
@@ -501,7 +562,11 @@ async fn delete_task(cx: &Cx, Form(input): Form<TaskIdForm>) -> Redirect {
501 mail(cx).after_activity(store, deletion.activity_id);562 mail(cx).after_activity(store, deletion.activity_id);
502 // Deleted; the referring `/?task=<id>` no longer names anything, so land563 // Deleted; the referring `/?task=<id>` no longer names anything, so land
503 // on the board itself rather than reopening a dead modal.564 // on the board itself rather than reopening a dead modal.
504- Ok((StatusCode::SEE_OTHER, [(header::LOCATION, "/".to_string())], Json(None)))565+ Ok((
566+ StatusCode::SEE_OTHER,
567+ [(header::LOCATION, "/".to_string())],
568+ Json(None),
569+ ))
505 }570 }
506 571
507 /// Deletes an attachment's row and its bytes. A hard delete, unlike572 /// Deletes an attachment's row and its bytes. A hard delete, unlike
@@ -659,20 +724,6 @@ pub(crate) mod glyph {
659 }724 }
660 }725 }
661 726
662-/// A person as a circle. Ported from `izlek-web/src/board.rs`'s `Avatar`; that
663-/// component has not crossed over into this crate yet, so this is a private
664-/// copy rather than a shared one.
665-async fn avatar(cx: &Cx, person: &Person, extra: &str) -> Result {
666- let initials = person.initials();
667- let tone = person.id.bytes().fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32)) % 5;
668- view! {
669- cx =>
670- <span class=(class!("avatar", format!("avatar-tone-{tone}"), extra))>
671- (initials)
672- </span>
673- }
674-}
675-
676 /// `Escape` for everything the task modal renders, topmost first: viewer →727 /// `Escape` for everything the task modal renders, topmost first: viewer →
677 /// delete confirm (`confirm=delete` in URL) → open edit popovers → modal728 /// delete confirm (`confirm=delete` in URL) → open edit popovers → modal
678 /// itself — one resolver at priority 90 on `window.__izlekEsc` (table on729 /// itself — one resolver at priority 90 on `window.__izlekEsc` (table on
@@ -768,7 +819,11 @@ async fn title_control(cx: &Cx, task: &TaskDetail, may_write: bool, lang: Lang)
768 async fn description_control(cx: &Cx, task: &TaskDetail, may_write: bool, lang: Lang) -> Result {819 async fn description_control(cx: &Cx, task: &TaskDetail, may_write: bool, lang: Lang) -> Result {
769 let empty = task.description.trim().is_empty();820 let empty = task.description.trim().is_empty();
770 let no_description = t(lang, Key::NoDescription).to_string();821 let no_description = t(lang, Key::NoDescription).to_string();
771- let prose = if empty { no_description.clone() } else { task.description.clone() };822+ let prose = if empty {
823+ no_description.clone()
824+ } else {
825+ task.description.clone()
826+ };
772 827
773 if !may_write {828 if !may_write {
774 return view! { cx => <p class=(class!("detail-prose", "detail-prose-empty" if empty))>(prose)</p> };829 return view! { cx => <p class=(class!("detail-prose", "detail-prose-empty" if empty))>(prose)</p> };
@@ -795,10 +850,18 @@ async fn description_control(cx: &Cx, task: &TaskDetail, may_write: bool, lang:
795 }850 }
796 }851 }
797 852
798-async fn deadline_control(cx: &Cx, task: &TaskDetail, today: Date, may_write: bool, lang: Lang) -> Result {853+async fn deadline_control(
854+ cx: &Cx,
855+ task: &TaskDetail,
856+ today: Date,
857+ may_write: bool,
858+ lang: Lang,
859+) -> Result {
799 let overdue = task.is_overdue(today);860 let overdue = task.is_overdue(today);
800 let label = match task.deadline_parts(today) {861 let label = match task.deadline_parts(today) {
801- Some(parts) if parts.state == DeadlineState::Overdue => format!("{} · {}", parts.date, t(lang, Key::Overdue)),862+ Some(parts) if parts.state == DeadlineState::Overdue => {
863+ format!("{} · {}", parts.date, t(lang, Key::Overdue))
864+ }
802 Some(parts) => parts.date,865 Some(parts) => parts.date,
803 None => t(lang, Key::NoDeadline).to_string(),866 None => t(lang, Key::NoDeadline).to_string(),
804 };867 };
@@ -956,12 +1019,18 @@ async fn datepicker_script(cx: &Cx, lang: Lang) -> Result {
956 view! { cx => <script>(Unescaped::new_unchecked(js))</script> }1019 view! { cx => <script>(Unescaped::new_unchecked(js))</script> }
957 }1020 }
958 1021
959-async fn assignee_chip(cx: &Cx, task_id: &str, person: &Person, may_write: bool, lang: Lang) -> Result {1022+async fn assignee_chip(
1023+ cx: &Cx,
1024+ task_id: &str,
1025+ person: &Person,
1026+ may_write: bool,
1027+ lang: Lang,
1028+) -> Result {
960 let remove_title = crate::i18n::take_off_this_task(lang, &person.display_name);1029 let remove_title = crate::i18n::take_off_this_task(lang, &person.display_name);
961 view! {1030 view! {
962 cx =>1031 cx =>
963 <span class="assignee-chip">1032 <span class="assignee-chip">
964- (avatar(cx, person, "avatar-sm").await?)1033+ (crate::layout::avatar(cx, person, "avatar-sm").await?)
965 <span class="assignee-name">(person.display_name.clone())</span>1034 <span class="assignee-name">(person.display_name.clone())</span>
966 if may_write {1035 if may_write {
967 <form class="assignee-drop" method="post" action="/api/unassign">1036 <form class="assignee-drop" method="post" action="/api/unassign">
@@ -992,7 +1061,7 @@ async fn assignee_picker(cx: &Cx, task_id: &str, people: &[Person], lang: Lang)
992 <input type="hidden" name="task_id" value=(task_id.to_string())>1061 <input type="hidden" name="task_id" value=(task_id.to_string())>
993 <input type="hidden" name="user_id" value=(person.id.clone())>1062 <input type="hidden" name="user_id" value=(person.id.clone())>
994 <button class="pop-row" type="submit">1063 <button class="pop-row" type="submit">
995- (avatar(cx, person, "avatar-sm").await?)1064+ (crate::layout::avatar(cx, person, "avatar-sm").await?)
996 <span class="pop-row-name">(person.display_name.clone())</span>1065 <span class="pop-row-name">(person.display_name.clone())</span>
997 </button>1066 </button>
998 </form>1067 </form>
@@ -1052,7 +1121,14 @@ async fn link_picker(cx: &Cx, task_id: &str, linkable: &[LinkTarget], lang: Lang
1052 }1121 }
1053 }1122 }
1054 1123
1055-async fn dep_row(cx: &Cx, task_id: &str, edge: &DependencyEdge, direction: Direction, may_write: bool, lang: Lang) -> Result {1124+async fn dep_row(
1125+ cx: &Cx,
1126+ task_id: &str,
1127+ edge: &DependencyEdge,
1128+ direction: Direction,
1129+ may_write: bool,
1130+ lang: Lang,
1131+) -> Result {
1056 let cleared = edge.is_cleared();1132 let cleared = edge.is_cleared();
1057 let note = match direction {1133 let note = match direction {
1058 Direction::BlockedBy => edge.blocked_by_label(),1134 Direction::BlockedBy => edge.blocked_by_label(),
@@ -1128,7 +1204,7 @@ async fn comment_row(cx: &Cx, comment: &Comment, zone: UtcOffset) -> Result {
1128 view! {1204 view! {
1129 cx =>1205 cx =>
1130 <div class="comment">1206 <div class="comment">
1131- (avatar(cx, &comment.author, "avatar-lg").await?)1207+ (crate::layout::avatar(cx, &comment.author, "avatar-lg").await?)
1132 <div class="comment-said">1208 <div class="comment-said">
1133 <div class="comment-head">1209 <div class="comment-head">
1134 <span class="comment-who">(comment.author.display_name.clone())</span>1210 <span class="comment-who">(comment.author.display_name.clone())</span>
@@ -1152,7 +1228,10 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool) -> Result
1152 // a gone task id is the common case — so the language is read1228 // a gone task id is the common case — so the language is read
1153 // the same way `board.rs`'s query-refusal branch does, English1229 // the same way `board.rs`'s query-refusal branch does, English
1154 // only when there truly is nobody signed in to read one off of.1230 // only when there truly is nobody signed in to read one off of.
1155- let lang = require_user(cx).await.map(|user| Lang::from_code(&user.language)).unwrap_or(Lang::En);1231+ let lang = require_user(cx)
1232+ .await
1233+ .map(|user| Lang::from_code(&user.language))
1234+ .unwrap_or(Lang::En);
1156 return view! {1235 return view! {
1157 cx =>1236 cx =>
1158 <div class="modal-scrim">1237 <div class="modal-scrim">
@@ -1179,14 +1258,24 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool) -> Result
1179 let unassigned: Vec<Person> = detail.unassigned().cloned().collect();1258 let unassigned: Vec<Person> = detail.unassigned().cloned().collect();
1180 let has_deps = !detail.blocked_by.is_empty() || !detail.blocks.is_empty();1259 let has_deps = !detail.blocked_by.is_empty() || !detail.blocks.is_empty();
1181 let accept = (!allowed_file_types.is_empty())1260 let accept = (!allowed_file_types.is_empty())
1182- .then(|| allowed_file_types.iter().map(|kind| format!(".{kind}")).collect::<Vec<_>>().join(","))1261+ .then(|| {
1262+ allowed_file_types
1263+ .iter()
1264+ .map(|kind| format!(".{kind}"))
1265+ .collect::<Vec<_>>()
1266+ .join(",")
1267+ })
1183 .unwrap_or_default();1268 .unwrap_or_default();
1184 1269
1185 // The delete confirmation is computed eagerly rather than fetched on1270 // The delete confirmation is computed eagerly rather than fetched on
1186 // demand: there is no script here to hold the intermediate "did they1271 // demand: there is no script here to hold the intermediate "did they
1187 // click delete yet" state, so the cost is already known by the time the1272 // click delete yet" state, so the cost is already known by the time the
1188 // disclosure opens.1273 // disclosure opens.
1189- let cost = if may_delete { accounts(cx).store().deletion_cost(&detail.id).await? } else { None };1274+ let cost = if may_delete {
1275+ accounts(cx).store().deletion_cost(&detail.id).await?
1276+ } else {
1277+ None
1278+ };
1190 1279
1191 view! {1280 view! {
1192 cx =>1281 cx =>
crates/izlek-web/src/files.rsmodified+76 -23
@@ -10,7 +10,9 @@ use time::OffsetDateTime;
10 use topcoat::context::Cx;10 use topcoat::context::Cx;
11 use topcoat::router::content::multipart::Multipart;11 use topcoat::router::content::multipart::Multipart;
12 use topcoat::router::request::headers as request_headers;12 use topcoat::router::request::headers as request_headers;
13-use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, query_params, route};13+use topcoat::router::{
14+ HeaderMap, HeaderValue, StatusCode, header, path_param, query_params, route,
15+};
14 16
15 use izlek_core::store::{NewAttachment, Store, User};17 use izlek_core::store::{NewAttachment, Store, User};
16 18
@@ -61,16 +63,13 @@ fn home(refusal: Refusal) -> (StatusCode, HeaderMap, Vec<u8>) {
61 /// carry a control character. What a browser calls a file is a label on a63 /// carry a control character. What a browser calls a file is a label on a
62 /// row, never a place to write bytes.64 /// row, never a place to write bytes.
63 fn label_of(file_name: &str) -> String {65 fn label_of(file_name: &str) -> String {
64- let base = file_name66+ let base = file_name.rsplit(['/', '\\']).next().unwrap_or(file_name);
65- .rsplit(['/', '\\'])
66- .next()
67- .unwrap_or(file_name);
68 base.chars().filter(|c| !c.is_control()).collect()67 base.chars().filter(|c| !c.is_control()).collect()
69 }68 }
70 69
71 /// What the bytes are, decided from the bytes themselves — never from the70 /// What the bytes are, decided from the bytes themselves — never from the
72 /// part's `content_type()`, which is whatever the browser felt like sending.71 /// part's `content_type()`, which is whatever the browser felt like sending.
73-fn sniff(bytes: &[u8]) -> &'static str {72+pub(crate) fn sniff(bytes: &[u8]) -> &'static str {
74 if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {73 if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
75 "image/png"74 "image/png"
76 } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {75 } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
@@ -87,7 +86,10 @@ fn sniff(bytes: &[u8]) -> &'static str {
87 "image/avif"86 "image/avif"
88 } else if bytes.len() >= 1287 } else if bytes.len() >= 12
89 && &bytes[4..8] == b"ftyp"88 && &bytes[4..8] == b"ftyp"
90- && matches!(&bytes[8..12], b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1")89+ && matches!(
90+ &bytes[8..12],
91+ b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1"
92+ )
91 {93 {
92 // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares;94 // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares;
93 // the brand at bytes 8..12 is what tells a photo from a video apart.95 // the brand at bytes 8..12 is what tells a photo from a video apart.
@@ -106,7 +108,11 @@ fn sniff(bytes: &[u8]) -> &'static str {
106 "audio/flac"108 "audio/flac"
107 } else if bytes.starts_with(b"OggS") {109 } else if bytes.starts_with(b"OggS") {
108 "audio/ogg"110 "audio/ogg"
109- } else if bytes.starts_with(b"ID3") || bytes.starts_with(&[0xFF, 0xFB]) || bytes.starts_with(&[0xFF, 0xF3]) || bytes.starts_with(&[0xFF, 0xF2]) {111+ } else if bytes.starts_with(b"ID3")
112+ || bytes.starts_with(&[0xFF, 0xFB])
113+ || bytes.starts_with(&[0xFF, 0xF3])
114+ || bytes.starts_with(&[0xFF, 0xF2])
115+ {
110 "audio/mpeg"116 "audio/mpeg"
111 } else if std::str::from_utf8(bytes).is_ok() {117 } else if std::str::from_utf8(bytes).is_ok() {
112 "text/plain"118 "text/plain"
@@ -127,7 +133,13 @@ fn disposition_of(file_name: &str, inline: bool) -> String {
127 let kind = if inline { "inline" } else { "attachment" };133 let kind = if inline { "inline" } else { "attachment" };
128 let ascii: String = file_name134 let ascii: String = file_name
129 .chars()135 .chars()
130- .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { c } else { '_' })136+ .map(|c| {
137+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
138+ c
139+ } else {
140+ '_'
141+ }
142+ })
131 .collect();143 .collect();
132 let mut encoded = String::new();144 let mut encoded = String::new();
133 for &byte in file_name.as_bytes() {145 for &byte in file_name.as_bytes() {
@@ -241,7 +253,10 @@ struct DownloadQuery {
241 /// Fields arrive in request order: `task_id` before `file`, so the task and253 /// Fields arrive in request order: `task_id` before `file`, so the task and
242 /// the workspace's limits are known before a byte of the file is kept.254 /// the workspace's limits are known before a byte of the file is kept.
243 #[route(POST "/files")]255 #[route(POST "/files")]
244-async fn upload(cx: &Cx, mut multipart: Multipart) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {256+async fn upload(
257+ cx: &Cx,
258+ mut multipart: Multipart,
259+) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
245 let user = match require_user(cx).await {260 let user = match require_user(cx).await {
246 Ok(user) => user,261 Ok(user) => user,
247 Err(refusal) => return Ok(home(refusal)),262 Err(refusal) => return Ok(home(refusal)),
@@ -392,11 +407,13 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
392 let mut headers = HeaderMap::new();407 let mut headers = HeaderMap::new();
393 headers.insert(408 headers.insert(
394 header::CONTENT_TYPE,409 header::CONTENT_TYPE,
395- HeaderValue::from_str(&row.mime_type).unwrap_or(HeaderValue::from_static("application/octet-stream")),410+ HeaderValue::from_str(&row.mime_type)
411+ .unwrap_or(HeaderValue::from_static("application/octet-stream")),
396 );412 );
397 headers.insert(413 headers.insert(
398 header::CONTENT_DISPOSITION,414 header::CONTENT_DISPOSITION,
399- HeaderValue::from_str(&disposition_of(&row.file_name, inline)).unwrap_or(HeaderValue::from_static("attachment")),415+ HeaderValue::from_str(&disposition_of(&row.file_name, inline))
416+ .unwrap_or(HeaderValue::from_static("attachment")),
400 );417 );
401 // Safari refuses to play a `<video>`/`<audio>` element without a `206`418 // Safari refuses to play a `<video>`/`<audio>` element without a `206`
402 // reply to its own `Range` probe; every other engine loses instant seek419 // reply to its own `Range` probe; every other engine loses instant seek
@@ -405,7 +422,9 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
405 headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));422 headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
406 423
407 let total = bytes.len() as u64;424 let total = bytes.len() as u64;
408- let range = request_headers(cx).get(header::RANGE).and_then(|v| v.to_str().ok());425+ let range = request_headers(cx)
426+ .get(header::RANGE)
427+ .and_then(|v| v.to_str().ok());
409 match range.and_then(|r| parse_range(r, total)) {428 match range.and_then(|r| parse_range(r, total)) {
410 Some(Ok((start, end))) => {429 Some(Ok((start, end))) => {
411 let slice = bytes[start as usize..=end as usize].to_vec();430 let slice = bytes[start as usize..=end as usize].to_vec();
@@ -435,16 +454,34 @@ mod tests {
435 assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png");454 assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png");
436 assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg");455 assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg");
437 assert_eq!(sniff(b"hello, this is plainly text"), "text/plain");456 assert_eq!(sniff(b"hello, this is plainly text"), "text/plain");
438- assert_eq!(sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), "application/octet-stream");457+ assert_eq!(
458+ sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]),
459+ "application/octet-stream"
460+ );
439 }461 }
440 462
441 #[test]463 #[test]
442 fn sniffs_the_media_types() {464 fn sniffs_the_media_types() {
443- assert_eq!(sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), "video/mp4");465+ assert_eq!(
444- assert_eq!(sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"), "image/avif");466+ sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"),
445- assert_eq!(sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"), "image/heic");467+ "video/mp4"
446- assert_eq!(sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"), "image/heic");468+ );
447- assert_eq!(sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"), "video/quicktime");469+ assert_eq!(
470+ sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"),
471+ "image/avif"
472+ );
473+ assert_eq!(
474+ sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"),
475+ "image/heic"
476+ );
477+ assert_eq!(
478+ sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"),
479+ "image/heic"
480+ );
481+ assert_eq!(
482+ sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"),
483+ "video/quicktime"
484+ );
448 assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm");485 assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm");
449 assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp");486 assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp");
450 assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav");487 assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav");
@@ -519,7 +556,11 @@ mod tests {
519 assert_eq!(viewer_kind("application/pdf"), Some(ViewerKind::Pdf));556 assert_eq!(viewer_kind("application/pdf"), Some(ViewerKind::Pdf));
520 assert_eq!(viewer_kind("text/plain"), None);557 assert_eq!(viewer_kind("text/plain"), None);
521 assert_eq!(viewer_kind("application/octet-stream"), None);558 assert_eq!(viewer_kind("application/octet-stream"), None);
522- assert_eq!(viewer_kind("image/heic"), None, "no decoder, no viewer element");559+ assert_eq!(
560+ viewer_kind("image/heic"),
561+ None,
562+ "no decoder, no viewer element"
563+ );
523 assert_eq!(viewer_kind("video/quicktime"), Some(ViewerKind::Video));564 assert_eq!(viewer_kind("video/quicktime"), Some(ViewerKind::Video));
524 }565 }
525 566
@@ -528,15 +569,27 @@ mod tests {
528 assert_eq!(parse_range("bytes=0-3", 10), Some(Ok((0, 3))));569 assert_eq!(parse_range("bytes=0-3", 10), Some(Ok((0, 3))));
529 assert_eq!(parse_range("bytes=-2", 10), Some(Ok((8, 9))));570 assert_eq!(parse_range("bytes=-2", 10), Some(Ok((8, 9))));
530 assert_eq!(parse_range("bytes=5-", 10), Some(Ok((5, 9))));571 assert_eq!(parse_range("bytes=5-", 10), Some(Ok((5, 9))));
531- assert_eq!(parse_range("bytes=5-100", 10), Some(Ok((5, 9))), "end clamps to the last byte");572+ assert_eq!(
573+ parse_range("bytes=5-100", 10),
574+ Some(Ok((5, 9))),
575+ "end clamps to the last byte"
576+ );
532 }577 }
533 578
534 #[test]579 #[test]
535 fn range_is_unsatisfiable_past_the_end_and_ignored_when_multi_range_or_malformed() {580 fn range_is_unsatisfiable_past_the_end_and_ignored_when_multi_range_or_malformed() {
536 assert_eq!(parse_range("bytes=10-20", 10), Some(Err(())));581 assert_eq!(parse_range("bytes=10-20", 10), Some(Err(())));
537 assert_eq!(parse_range("bytes=-0", 10), Some(Err(())));582 assert_eq!(parse_range("bytes=-0", 10), Some(Err(())));
538- assert_eq!(parse_range("bytes=0-3,5-8", 10), None, "multi-range falls back to a full body");583+ assert_eq!(
584+ parse_range("bytes=0-3,5-8", 10),
585+ None,
586+ "multi-range falls back to a full body"
587+ );
539 assert_eq!(parse_range("nonsense", 10), None);588 assert_eq!(parse_range("nonsense", 10), None);
540- assert_eq!(parse_range("bytes=0-3", 0), None, "an empty file has no range to satisfy");589+ assert_eq!(
590+ parse_range("bytes=0-3", 0),
591+ None,
592+ "an empty file has no range to satisfy"
593+ );
541 }594 }
542 }595 }
crates/izlek-web/src/i18n.rsmodified+17 -3
@@ -101,6 +101,8 @@ pub enum Key {
101 101
102 // settings.rs102 // settings.rs
103 YourProfile,103 YourProfile,
104+ Picture,
105+ Remove,
104 DisplayNameLabel,106 DisplayNameLabel,
105 EmailLabel,107 EmailLabel,
106 TimezoneLabel,108 TimezoneLabel,
@@ -431,6 +433,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
431 433
432 (YourProfile, En) => "Your profile",434 (YourProfile, En) => "Your profile",
433 (YourProfile, Tr) => "Profilin",435 (YourProfile, Tr) => "Profilin",
436+ (Picture, En) => "Picture",
437+ (Picture, Tr) => "Resim",
438+ (Remove, En) => "Remove",
439+ (Remove, Tr) => "Kaldır",
434 (DisplayNameLabel, En) => "DISPLAY NAME",440 (DisplayNameLabel, En) => "DISPLAY NAME",
435 (DisplayNameLabel, Tr) => "GÖRÜNEN AD",441 (DisplayNameLabel, Tr) => "GÖRÜNEN AD",
436 (EmailLabel, En) => "EMAIL",442 (EmailLabel, En) => "EMAIL",
@@ -801,8 +807,14 @@ fn month_names(lang: Lang) -> [&'static str; 12] {
801 /// literals, embedded once per page in its inline script — the grid itself807 /// literals, embedded once per page in its inline script — the grid itself
802 /// is built in JS (see `detail.rs`'s `datepicker_script`).808 /// is built in JS (see `detail.rs`'s `datepicker_script`).
803 pub fn datepicker_js_literals(lang: Lang) -> (String, String) {809 pub fn datepicker_js_literals(lang: Lang) -> (String, String) {
804- let months = month_names(lang).map(|name| format!("\"{name}\"")).join(",");810+ let months = month_names(lang)
805- let weekdays = t(lang, Key::WeekdayInitials).split(',').map(|initial| format!("\"{initial}\"")).collect::<Vec<_>>().join(",");811+ .map(|name| format!("\"{name}\""))
812+ .join(",");
813+ let weekdays = t(lang, Key::WeekdayInitials)
814+ .split(',')
815+ .map(|initial| format!("\"{initial}\""))
816+ .collect::<Vec<_>>()
817+ .join(",");
806 (format!("[{months}]"), format!("[{weekdays}]"))818 (format!("[{months}]"), format!("[{weekdays}]"))
807 }819 }
808 820
@@ -936,7 +948,9 @@ pub fn moved_not_watched_label(lang: Lang, to: &str, watched: &str) -> String {
936 pub fn freed_not_watched_label(lang: Lang, watched: &str) -> String {948 pub fn freed_not_watched_label(lang: Lang, watched: &str) -> String {
937 match lang {949 match lang {
938 Lang::En => format!("freed a task, rule watches a move to {watched}"),950 Lang::En => format!("freed a task, rule watches a move to {watched}"),
939- Lang::Tr => format!("bir görevin engelini kaldırdı, kural {watched} sütununa taşınmasını izliyor"),951+ Lang::Tr => {
952+ format!("bir görevin engelini kaldırdı, kural {watched} sütununa taşınmasını izliyor")
953+ }
940 }954 }
941 }955 }
942 956
crates/izlek-web/src/layout.rsmodified+43 -7
@@ -6,32 +6,68 @@ use topcoat::{
6 asset::{Asset, asset},6 asset::{Asset, asset},
7 context::Cx,7 context::Cx,
8 router::{8 router::{
9- StatusCode, page,9+ StatusCode,
10- layout,
11 error::{NotFoundError, not_found},10 error::{NotFoundError, not_found},
11+ layout, page,
12 },12 },
13 view::{Unescaped, view},13 view::{Unescaped, view},
14 };14 };
15 15
16+use izlek_core::board::Person;
17+
16 use crate::i18n::{Key, Lang, t};18 use crate::i18n::{Key, Lang, t};
17 use crate::server::current_user;19 use crate::server::current_user;
18 20
21+/// A person as a circle (or, on the Instrument skin, a square) — the initials
22+/// avatar when there is no photo, an `<img>` reading `/photo/{id}` otherwise.
23+/// Shared by the board, the modal and every topbar user menu.
24+pub(crate) async fn avatar(cx: &Cx, person: &Person, extra: &str) -> Result {
25+ let tone = person
26+ .id
27+ .bytes()
28+ .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32))
29+ % 5;
30+ let class = format!("avatar avatar-tone-{tone} {extra}");
31+ let name = person.display_name.clone();
32+ if person.has_photo {
33+ let src = format!("/photo/{}", person.id);
34+ view! {
35+ cx =>
36+ <img class=(class) src=(src) alt=(name.clone()) data-name=(name)>
37+ }
38+ } else {
39+ let initials = person.initials();
40+ view! {
41+ cx =>
42+ <span class=(class) data-name=(name)>(initials)</span>
43+ }
44+ }
45+}
46+
19 /// The topbar's signed-in identity: the display name, opening on hover or47 /// The topbar's signed-in identity: the display name, opening on hover or
20 /// focus onto details (name, address, role), settings and sign-out. Shared48 /// focus onto details (name, address, role), settings and sign-out. Shared
21 /// by every signed-in page's topbar (board, settings, mail rules, logs).49 /// by every signed-in page's topbar (board, settings, mail rules, logs).
22-pub async fn user_menu(cx: &Cx, display_name: &str, email: &str, role: izlek_core::Role, lang: Lang) -> Result {50+pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result {
23- let role_key = match role {51+ let role_key = match me.role {
24 izlek_core::Role::Admin => Key::RoleAdminOption,52 izlek_core::Role::Admin => Key::RoleAdminOption,
25 izlek_core::Role::Member => Key::RoleMemberOption,53 izlek_core::Role::Member => Key::RoleMemberOption,
26 izlek_core::Role::Viewer => Key::RoleViewerOption,54 izlek_core::Role::Viewer => Key::RoleViewerOption,
27 };55 };
56+ let person = izlek_core::board::Person {
57+ id: me.id.clone(),
58+ display_name: me.display_name.clone(),
59+ has_photo: me.has_photo,
60+ };
28 view! {61 view! {
29 cx =>62 cx =>
30 <div class="user-menu">63 <div class="user-menu">
31- <button type="button" class="user-menu-trigger">(display_name.to_string())</button>64+ <button type="button" class="user-menu-trigger">
65+ (avatar(cx, &person, "").await?)
66+ (me.display_name.clone())
67+ </button>
32 <div class="user-menu-panel">68 <div class="user-menu-panel">
33- <div class="user-menu-name">(display_name.to_string())</div>69+ <div class="user-menu-name">(me.display_name.clone())</div>
34- <div class="user-menu-email">(email.to_string())</div>70+ <div class="user-menu-email">(me.email.clone())</div>
35 <div class="user-menu-role">(t(lang, role_key))</div>71 <div class="user-menu-role">(t(lang, role_key))</div>
36 <div class="user-menu-divider"></div>72 <div class="user-menu-divider"></div>
37 <a class="user-menu-item" href="/settings">(t(lang, Key::Settings))</a>73 <a class="user-menu-item" href="/settings">(t(lang, Key::Settings))</a>
crates/izlek-web/src/lib.rsmodified+3 -2
@@ -11,8 +11,9 @@ pub mod files;
11 pub mod i18n;11 pub mod i18n;
12 pub mod layout;12 pub mod layout;
13 pub mod logs;13 pub mod logs;
14-pub mod rules;
15-pub mod settings;
16 pub mod pages;14 pub mod pages;
15+pub mod photo;
16+pub mod rules;
17 pub mod server;17 pub mod server;
18+pub mod settings;
18 pub mod smtp;19 pub mod smtp;
crates/izlek-web/src/logs.rsmodified+20 -6
@@ -166,7 +166,8 @@ async fn decision_detail(
166 ) -> std::result::Result<String, izlek_core::store::StoreError> {166 ) -> std::result::Result<String, izlek_core::store::StoreError> {
167 use izlek_core::store::MailOutcome;167 use izlek_core::store::MailOutcome;
168 168
169- if detail.is_empty() || !matches!(outcome, MailOutcome::NoRecipients | MailOutcome::NotMatched) {169+ if detail.is_empty() || !matches!(outcome, MailOutcome::NoRecipients | MailOutcome::NotMatched)
170+ {
170 return Ok(detail.to_string());171 return Ok(detail.to_string());
171 }172 }
172 match (outcome, detail) {173 match (outcome, detail) {
@@ -206,7 +207,11 @@ async fn decision_detail(
206 if let Some(rest) = detail.strip_prefix("moved:") {207 if let Some(rest) = detail.strip_prefix("moved:") {
207 let mut parts = rest.splitn(2, ':');208 let mut parts = rest.splitn(2, ':');
208 if let (Some(to), Some(watched)) = (parts.next(), parts.next()) {209 if let (Some(to), Some(watched)) = (parts.next(), parts.next()) {
209- return Ok(crate::i18n::moved_not_watched_label(lang, &name(to), &name(watched)));210+ return Ok(crate::i18n::moved_not_watched_label(
211+ lang,
212+ &name(to),
213+ &name(watched),
214+ ));
210 }215 }
211 }216 }
212 if let Some(watched) = detail.strip_prefix("unblocked:") {217 if let Some(watched) = detail.strip_prefix("unblocked:") {
@@ -226,7 +231,11 @@ async fn decision_detail(
226 return Ok(detail.to_string());231 return Ok(detail.to_string());
227 };232 };
228 let event_word = crate::i18n::activity_kind_word(lang, kind);233 let event_word = crate::i18n::activity_kind_word(lang, kind);
229- return Ok(crate::i18n::happened_not_watched_label(lang, &event_word, &watched));234+ return Ok(crate::i18n::happened_not_watched_label(
235+ lang,
236+ &event_word,
237+ &watched,
238+ ));
230 }239 }
231 Ok(detail.to_string())240 Ok(detail.to_string())
232 }241 }
@@ -306,7 +315,10 @@ async fn snapshot(cx: &Cx) -> Result<std::result::Result<LogsSnapshot, Refusal>>
306 outcome_kind: decision.outcome.as_str().to_string(),315 outcome_kind: decision.outcome.as_str().to_string(),
307 detail,316 detail,
308 };317 };
309- if let Some(group) = decisions.iter_mut().find(|g| g.event_id == decision.event_id) {318+ if let Some(group) = decisions
319+ .iter_mut()
320+ .find(|g| g.event_id == decision.event_id)
321+ {
310 group.verdicts.push(verdict);322 group.verdicts.push(verdict);
311 continue;323 continue;
312 }324 }
@@ -331,7 +343,9 @@ async fn snapshot(cx: &Cx) -> Result<std::result::Result<LogsSnapshot, Refusal>>
331 .into_iter()343 .into_iter()
332 .map(|line| ActivityRow {344 .map(|line| ActivityRow {
333 at: izlek_core::detail::moment_label_in(line.at, zone),345 at: izlek_core::detail::moment_label_in(line.at, zone),
334- actor: line.actor_name.unwrap_or_else(|| t(lang, Key::TheSystem).to_string()),346+ actor: line
347+ .actor_name
348+ .unwrap_or_else(|| t(lang, Key::TheSystem).to_string()),
335 sentence: activity_sentence(&line.kind, &line.detail, lang),349 sentence: activity_sentence(&line.kind, &line.detail, lang),
336 title: line.title,350 title: line.title,
337 })351 })
@@ -393,7 +407,7 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot) -> Result {
393 </a>407 </a>
394 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Logs, lang).await?)408 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Logs, lang).await?)
395 <div class="spacer"></div>409 <div class="spacer"></div>
396- (crate::layout::user_menu(cx, &me.display_name, &me.email, me.role, lang).await?)410+ (crate::layout::user_menu(cx, &me, lang).await?)
397 </header>411 </header>
398 412
399 <div class="settings-shell">413 <div class="settings-shell">
crates/izlek-web/src/main.rsmodified+11 -2
@@ -53,7 +53,14 @@ async fn main() {
53 53
54 let router = Router::builder()54 let router = Router::builder()
55 .discover()55 .discover()
56- .layer(BodyLimit::max(izlek_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024).at("/files"))56+ .layer(
57+ BodyLimit::max(izlek_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024)
58+ .at("/files"),
59+ )
60+ .layer(
61+ BodyLimit::max(izlek_web::settings::WIDEST_PHOTO_MB as usize * 1024 * 1024)
62+ .at("/api/profile_photo"),
63+ )
57 .cookies()64 .cookies()
58 .assets(AssetBundle::load().expect("failed to load the asset bundle"))65 .assets(AssetBundle::load().expect("failed to load the asset bundle"))
59 .app_context(accounts)66 .app_context(accounts)
@@ -66,7 +73,9 @@ async fn main() {
66 let listener = tokio::net::TcpListener::bind(config.listen)73 let listener = tokio::net::TcpListener::bind(config.listen)
67 .await74 .await
68 .expect("failed to bind the listen address");75 .expect("failed to bind the listen address");
69- topcoat::serve(listener, router).await.expect("server error");76+ topcoat::serve(listener, router)
77+ .await
78+ .expect("server error");
70 }79 }
71 80
72 /// Retries what a mail server refused earlier and picks up anything a crash81 /// Retries what a mail server refused earlier and picks up anything a crash
crates/izlek-web/src/pages.rsmodified+5 -1
@@ -29,7 +29,11 @@ async fn landing(cx: &Cx) -> Result {
29 Ok(Some(user)) => signed_in_shell(cx, user.clone()).await,29 Ok(Some(user)) => signed_in_shell(cx, user.clone()).await,
30 Ok(None) => {30 Ok(None) => {
31 let claimed = accounts(cx).store().owner().await?.is_some();31 let claimed = accounts(cx).store().owner().await?.is_some();
32- if claimed { sign_in_card(cx).await } else { setup_card(cx).await }32+ if claimed {
33+ sign_in_card(cx).await
34+ } else {
35+ setup_card(cx).await
36+ }
33 }37 }
34 Err(_) => view! {38 Err(_) => view! {
35 cx =>39 cx =>
crates/izlek-web/src/photo.rsadded+141 -0
@@ -0,0 +1,141 @@
1+//! Profile photo upload, removal and serving. Sibling to `files.rs`, whose
2+//! multipart parsing and mime-sniffing it reuses rather than re-implements.
3+
4+use topcoat::context::Cx;
5+use topcoat::router::content::multipart::Multipart;
6+use topcoat::router::request::headers as request_headers;
7+use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route};
8+
9+use crate::files::sniff;
10+use crate::server::{Refusal, accounts, require_user};
11+use crate::settings::saved_or_refused;
12+
13+path_param!(user_id);
14+
15+fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) {
16+ (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())
17+}
18+
19+/// Sets the signed-in person's own photo. Nobody else's — the id comes from
20+/// the session, never from the form.
21+#[route(POST "/api/profile_photo")]
22+async fn upload(
23+ cx: &Cx,
24+ mut multipart: Multipart,
25+) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
26+ let user = match require_user(cx).await {
27+ Ok(user) => user,
28+ Err(refusal) => return Ok(saved_or_refused("profile_photo", Some(refusal))),
29+ };
30+ let store = accounts(cx).store().clone();
31+ let Ok(Some(workspace)) = store.workspace().await else {
32+ return Ok(saved_or_refused(
33+ "profile_photo",
34+ Some(Refusal::Unavailable),
35+ ));
36+ };
37+ let limit = workspace.photo_limit_bytes;
38+
39+ loop {
40+ let field = match multipart.next_field().await {
41+ Ok(Some(field)) => field,
42+ Ok(None) => return Ok(saved_or_refused("profile_photo", Some(Refusal::NoFile))),
43+ Err(_) => return Ok(saved_or_refused("profile_photo", Some(Refusal::NoFile))),
44+ };
45+ if field.file_name().is_none() {
46+ continue;
47+ }
48+ let mut field = field;
49+ let mut collected = Vec::new();
50+ loop {
51+ match field.chunk().await {
52+ Ok(Some(chunk)) => {
53+ if (collected.len() + chunk.len()) as u64 > limit {
54+ return Ok(saved_or_refused("profile_photo", Some(Refusal::FileTooBig)));
55+ }
56+ collected.extend_from_slice(&chunk);
57+ }
58+ Ok(None) => break,
59+ Err(_) => return Ok(saved_or_refused("profile_photo", Some(Refusal::FileTooBig))),
60+ }
61+ }
62+ let mime = sniff(&collected);
63+ if !matches!(
64+ mime,
65+ "image/png" | "image/jpeg" | "image/gif" | "image/webp" | "image/avif"
66+ ) {
67+ return Ok(saved_or_refused("profile_photo", Some(Refusal::NotAnImage)));
68+ }
69+ return Ok(match store.set_photo(&user.id, &collected, mime).await {
70+ Ok(()) => saved_or_refused("profile_photo", None),
71+ Err(_) => saved_or_refused("profile_photo", Some(Refusal::Unavailable)),
72+ });
73+ }
74+}
75+
76+/// Clears the signed-in person's own photo.
77+#[route(POST "/api/delete_profile_photo")]
78+async fn delete(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
79+ let user = match require_user(cx).await {
80+ Ok(user) => user,
81+ Err(refusal) => return Ok(saved_or_refused("delete_profile_photo", Some(refusal))),
82+ };
83+ let store = accounts(cx).store().clone();
84+ Ok(match store.clear_photo(&user.id).await {
85+ Ok(()) => saved_or_refused("delete_profile_photo", None),
86+ Err(_) => saved_or_refused("delete_profile_photo", Some(Refusal::Unavailable)),
87+ })
88+}
89+
90+/// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only
91+/// this server ever writes.
92+fn fnv1a(bytes: &[u8]) -> u64 {
93+ let mut hash: u64 = 0xcbf29ce484222325;
94+ for &b in bytes {
95+ hash ^= b as u64;
96+ hash = hash.wrapping_mul(0x100000001b3);
97+ }
98+ hash
99+}
100+
101+/// Serves one person's photo, or the not-found a stranger to their workspace
102+/// would see for a person with none at all — never `403`, same reasoning as
103+/// `files.rs`'s `download`.
104+#[route(GET "/photo/{user_id}")]
105+async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
106+ let user_id: &str = path_param::<UserId>(cx);
107+
108+ let asking = match require_user(cx).await {
109+ Ok(user) => user,
110+ Err(_) => return Ok(not_found()),
111+ };
112+
113+ let store = accounts(cx).store().clone();
114+ let Ok(Some(target)) = store.user(user_id).await else {
115+ return Ok(not_found());
116+ };
117+ if target.workspace_id != asking.workspace_id || !target.has_photo {
118+ return Ok(not_found());
119+ }
120+ let Ok(Some((bytes, mime))) = store.photo(user_id).await else {
121+ return Ok(not_found());
122+ };
123+
124+ let etag = format!("\"{:x}\"", fnv1a(&bytes));
125+ let mut headers = HeaderMap::new();
126+ headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap());
127+
128+ let if_none_match = request_headers(cx)
129+ .get(header::IF_NONE_MATCH)
130+ .and_then(|v| v.to_str().ok());
131+ if if_none_match == Some(etag.as_str()) {
132+ return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new()));
133+ }
134+
135+ headers.insert(
136+ header::CONTENT_TYPE,
137+ HeaderValue::from_str(&mime)
138+ .unwrap_or(HeaderValue::from_static("application/octet-stream")),
139+ );
140+ Ok((StatusCode::OK, headers, bytes))
141+}
crates/izlek-web/src/rules.rsmodified+168 -45
@@ -141,15 +141,34 @@ fn audience_of(word: &str) -> std::result::Result<Audience, Refusal> {
141 /// this module does not reach into `crate::settings::Sender` so it stays141 /// this module does not reach into `crate::settings::Sender` so it stays
142 /// independent of that screen's own shape.142 /// independent of that screen's own shape.
143 fn sender_connected(workspace: &Workspace) -> bool {143 fn sender_connected(workspace: &Workspace) -> bool {
144- !workspace.smtp_host.as_deref().unwrap_or_default().trim().is_empty()144+ !workspace
145- && !workspace.smtp_username.as_deref().unwrap_or_default().trim().is_empty()145+ .smtp_host
146- && !workspace.smtp_from_address.as_deref().unwrap_or_default().trim().is_empty()146+ .as_deref()
147+ .unwrap_or_default()
148+ .trim()
149+ .is_empty()
150+ && !workspace
151+ .smtp_username
152+ .as_deref()
153+ .unwrap_or_default()
154+ .trim()
155+ .is_empty()
156+ && !workspace
157+ .smtp_from_address
158+ .as_deref()
159+ .unwrap_or_default()
160+ .trim()
161+ .is_empty()
147 && workspace.smtp_password_set162 && workspace.smtp_password_set
148 }163 }
149 164
150 /// Splits a trigger into the sentence halves the screen prints, ported165 /// Splits a trigger into the sentence halves the screen prints, ported
151 /// verbatim from `current_rules`'s match in `izlek-web/src/rules.rs`.166 /// verbatim from `current_rules`'s match in `izlek-web/src/rules.rs`.
152-fn sentence_of(trigger: &Trigger, columns: &[Column], lang: Lang) -> (String, String, String, Option<String>) {167+fn sentence_of(
168+ trigger: &Trigger,
169+ columns: &[Column],
170+ lang: Lang,
171+) -> (String, String, String, Option<String>) {
153 match trigger {172 match trigger {
154 Trigger::StatusBecomes(column_id) => (173 Trigger::StatusBecomes(column_id) => (
155 t(lang, Key::WhenStatusBecomes).to_string(),174 t(lang, Key::WhenStatusBecomes).to_string(),
@@ -169,12 +188,18 @@ fn sentence_of(trigger: &Trigger, columns: &[Column], lang: Lang) -> (String, St
169 "unblocked".to_string(),188 "unblocked".to_string(),
170 None,189 None,
171 ),190 ),
172- Trigger::Created => {191+ Trigger::Created => (
173- (t(lang, Key::WhenTaskCreated).to_string(), String::new(), "created".to_string(), None)192+ t(lang, Key::WhenTaskCreated).to_string(),
174- }193+ String::new(),
175- Trigger::Assigned => {194+ "created".to_string(),
176- (t(lang, Key::WhenSomeoneAssigned).to_string(), String::new(), "assigned".to_string(), None)195+ None,
177- }196+ ),
197+ Trigger::Assigned => (
198+ t(lang, Key::WhenSomeoneAssigned).to_string(),
199+ String::new(),
200+ "assigned".to_string(),
201+ None,
202+ ),
178 Trigger::Unassigned => (203 Trigger::Unassigned => (
179 t(lang, Key::WhenSomeoneUnassigned).to_string(),204 t(lang, Key::WhenSomeoneUnassigned).to_string(),
180 String::new(),205 String::new(),
@@ -199,37 +224,65 @@ fn sentence_of(trigger: &Trigger, columns: &[Column], lang: Lang) -> (String, St
199 "deadline_cleared".to_string(),224 "deadline_cleared".to_string(),
200 None,225 None,
201 ),226 ),
202- Trigger::Retitled => {227+ Trigger::Retitled => (
203- (t(lang, Key::WhenTaskRenamed).to_string(), String::new(), "retitled".to_string(), None)228+ t(lang, Key::WhenTaskRenamed).to_string(),
204- }229+ String::new(),
205- Trigger::Linked => {230+ "retitled".to_string(),
206- (t(lang, Key::WhenTaskLinked).to_string(), String::new(), "linked".to_string(), None)231+ None,
207- }232+ ),
233+ Trigger::Linked => (
234+ t(lang, Key::WhenTaskLinked).to_string(),
235+ String::new(),
236+ "linked".to_string(),
237+ None,
238+ ),
208 Trigger::Unlinked => (239 Trigger::Unlinked => (
209 t(lang, Key::WhenTaskUnlinked).to_string(),240 t(lang, Key::WhenTaskUnlinked).to_string(),
210 String::new(),241 String::new(),
211 "unlinked".to_string(),242 "unlinked".to_string(),
212 None,243 None,
213 ),244 ),
214- Trigger::Deleted => {245+ Trigger::Deleted => (
215- (t(lang, Key::WhenTaskDeleted).to_string(), String::new(), "deleted".to_string(), None)246+ t(lang, Key::WhenTaskDeleted).to_string(),
216- }247+ String::new(),
248+ "deleted".to_string(),
249+ None,
250+ ),
217 }251 }
218 }252 }
219 253
220 /// Every rule on the board, switched-off ones included, with the columns a new254 /// Every rule on the board, switched-off ones included, with the columns a new
221 /// rule may name — shared by the page and `current_rules`, so the two never255 /// rule may name — shared by the page and `current_rules`, so the two never
222 /// drift apart.256 /// drift apart.
223-async fn snapshot_of(store: &Arc<dyn Store>, user: &User) -> std::result::Result<RulesSnapshot, Refusal> {257+async fn snapshot_of(
258+ store: &Arc<dyn Store>,
259+ user: &User,
260+) -> std::result::Result<RulesSnapshot, Refusal> {
224 let lang = Lang::from_code(&user.language);261 let lang = Lang::from_code(&user.language);
225 let zone = izlek_core::detail::parse_zone(&user.timezone);262 let zone = izlek_core::detail::parse_zone(&user.timezone);
226- let Some(board) = store.board(&user.workspace_id).await.map_err(|_| Refusal::Unavailable)? else {263+ let Some(board) = store
264+ .board(&user.workspace_id)
265+ .await
266+ .map_err(|_| Refusal::Unavailable)?
267+ else {
227 return Err(Refusal::Unavailable);268 return Err(Refusal::Unavailable);
228 };269 };
229- let columns = store.columns(&board.id).await.map_err(|_| Refusal::Unavailable)?;270+ let columns = store
230- let rules = store.mail_rules(&board.id).await.map_err(|_| Refusal::Unavailable)?;271+ .columns(&board.id)
231- let last_sent = store.mail_rule_last_sent(&board.id).await.map_err(|_| Refusal::Unavailable)?;272+ .await
232- let last_decision = store.mail_rule_last_decision().await.map_err(|_| Refusal::Unavailable)?;273+ .map_err(|_| Refusal::Unavailable)?;
274+ let rules = store
275+ .mail_rules(&board.id)
276+ .await
277+ .map_err(|_| Refusal::Unavailable)?;
278+ let last_sent = store
279+ .mail_rule_last_sent(&board.id)
280+ .await
281+ .map_err(|_| Refusal::Unavailable)?;
282+ let last_decision = store
283+ .mail_rule_last_decision()
284+ .await
285+ .map_err(|_| Refusal::Unavailable)?;
233 let sender_connected = store286 let sender_connected = store
234 .workspace()287 .workspace()
235 .await288 .await
@@ -268,7 +321,10 @@ async fn snapshot_of(store: &Arc<dyn Store>, user: &User) -> std::result::Result
268 rules: lines,321 rules: lines,
269 columns: columns322 columns: columns
270 .into_iter()323 .into_iter()
271- .map(|column| ColumnChoice { id: column.id, name: column.name })324+ .map(|column| ColumnChoice {
325+ id: column.id,
326+ name: column.name,
327+ })
272 .collect(),328 .collect(),
273 sender_connected,329 sender_connected,
274 })330 })
@@ -280,7 +336,10 @@ async fn snapshot_of(store: &Arc<dyn Store>, user: &User) -> std::result::Result
280 /// A rule id is opaque and arrives from the browser, so "not yours" and "not a336 /// A rule id is opaque and arrives from the browser, so "not yours" and "not a
281 /// rule" are the same answer: neither tells the caller whether the id exists337 /// rule" are the same answer: neither tells the caller whether the id exists
282 /// somewhere else.338 /// somewhere else.
283-async fn rule_of_this_workspace(cx: &Cx, rule_id: &str) -> std::result::Result<Arc<dyn Store>, Refusal> {339+async fn rule_of_this_workspace(
340+ cx: &Cx,
341+ rule_id: &str,
342+) -> std::result::Result<Arc<dyn Store>, Refusal> {
284 let user = require_admin(cx).await?;343 let user = require_admin(cx).await?;
285 let store = accounts(cx).store().clone();344 let store = accounts(cx).store().clone();
286 let board = store345 let board = store
@@ -326,7 +385,11 @@ fn back_to(cx: &Cx) -> String {
326 type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;385 type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;
327 386
328 fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {387 fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
329- Ok((StatusCode::SEE_OTHER, [(header::LOCATION, back_to(cx))], Json(refusal)))388+ Ok((
389+ StatusCode::SEE_OTHER,
390+ [(header::LOCATION, back_to(cx))],
391+ Json(refusal),
392+ ))
330 }393 }
331 394
332 #[derive(Deserialize)]395 #[derive(Deserialize)]
@@ -365,9 +428,15 @@ async fn create_rule(cx: &Cx, Form(input): Form<CreateRuleForm>) -> Redirect {
365 Ok(Some(board)) => board,428 Ok(Some(board)) => board,
366 _ => return redirect(cx, Some(Refusal::Unavailable)),429 _ => return redirect(cx, Some(Refusal::Unavailable)),
367 };430 };
368- let column_id = if input.column_id.trim().is_empty() { None } else { Some(input.column_id) };431+ let column_id = if input.column_id.trim().is_empty() {
432+ None
433+ } else {
434+ Some(input.column_id)
435+ };
369 if input.trigger == "status" {436 if input.trigger == "status" {
370- let Some(column_id) = &column_id else { return redirect(cx, Some(Refusal::Forbidden)) };437+ let Some(column_id) = &column_id else {
438+ return redirect(cx, Some(Refusal::Forbidden));
439+ };
371 let columns = match store.columns(&board.id).await {440 let columns = match store.columns(&board.id).await {
372 Ok(columns) => columns,441 Ok(columns) => columns,
373 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),442 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),
@@ -438,9 +507,15 @@ async fn update_rule(cx: &Cx, Form(input): Form<UpdateRuleForm>) -> Redirect {
438 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),507 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),
439 }508 }
440 509
441- let column_id = if input.column_id.trim().is_empty() { None } else { Some(input.column_id) };510+ let column_id = if input.column_id.trim().is_empty() {
511+ None
512+ } else {
513+ Some(input.column_id)
514+ };
442 if input.trigger == "status" {515 if input.trigger == "status" {
443- let Some(column_id) = &column_id else { return redirect(cx, Some(Refusal::Forbidden)) };516+ let Some(column_id) = &column_id else {
517+ return redirect(cx, Some(Refusal::Forbidden));
518+ };
444 let columns = match store.columns(&board.id).await {519 let columns = match store.columns(&board.id).await {
445 Ok(columns) => columns,520 Ok(columns) => columns,
446 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),521 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),
@@ -483,7 +558,11 @@ async fn set_rule_enabled(cx: &Cx, Form(input): Form<SetRuleEnabledForm>) -> Red
483 Ok(store) => store,558 Ok(store) => store,
484 Err(refusal) => return redirect(cx, Some(refusal)),559 Err(refusal) => return redirect(cx, Some(refusal)),
485 };560 };
486- if store.set_mail_rule_enabled(&input.rule_id, input.enabled == "true").await.is_err() {561+ if store
562+ .set_mail_rule_enabled(&input.rule_id, input.enabled == "true")
563+ .await
564+ .is_err()
565+ {
487 return redirect(cx, Some(Refusal::Unavailable));566 return redirect(cx, Some(Refusal::Unavailable));
488 }567 }
489 redirect(cx, None)568 redirect(cx, None)
@@ -524,16 +603,32 @@ struct RulesQuery {
524 /// server-side, from whichever trigger the form starts on (the existing603 /// server-side, from whichever trigger the form starts on (the existing
525 /// rule's, or "status" for a fresh one), since there is no script to flip it604 /// rule's, or "status" for a fresh one), since there is no script to flip it
526 /// as the admin changes the select.605 /// as the admin changes the select.
527-async fn rule_form(cx: &Cx, columns: &[ColumnChoice], existing: Option<&RuleLine>, refusal: Option<&Refusal>, lang: Lang) -> Result {606+async fn rule_form(
607+ cx: &Cx,
608+ columns: &[ColumnChoice],
609+ existing: Option<&RuleLine>,
610+ refusal: Option<&Refusal>,
611+ lang: Lang,
612+) -> Result {
528 let is_edit = existing.is_some();613 let is_edit = existing.is_some();
529- let action = if is_edit { "/api/update_rule" } else { "/api/create_rule" };614+ let action = if is_edit {
530- let trigger_kind = existing.map(|rule| rule.trigger_kind.as_str()).unwrap_or("status");615+ "/api/update_rule"
616+ } else {
617+ "/api/create_rule"
618+ };
619+ let trigger_kind = existing
620+ .map(|rule| rule.trigger_kind.as_str())
621+ .unwrap_or("status");
531 let column_id = existing622 let column_id = existing
532 .and_then(|rule| rule.column_id.as_deref())623 .and_then(|rule| rule.column_id.as_deref())
533 .or_else(|| columns.first().map(|column| column.id.as_str()))624 .or_else(|| columns.first().map(|column| column.id.as_str()))
534 .unwrap_or_default();625 .unwrap_or_default();
535- let subject = existing.map(|rule| rule.subject.as_str()).unwrap_or_default();626+ let subject = existing
536- let audience_kind = existing.map(|rule| rule.audience_kind.as_str()).unwrap_or("assignees");627+ .map(|rule| rule.subject.as_str())
628+ .unwrap_or_default();
629+ let audience_kind = existing
630+ .map(|rule| rule.audience_kind.as_str())
631+ .unwrap_or("assignees");
537 let include_task_details = existing.is_some_and(|rule| rule.include_task_details);632 let include_task_details = existing.is_some_and(|rule| rule.include_task_details);
538 633
539 view! {634 view! {
@@ -614,7 +709,12 @@ async fn rule_form(cx: &Cx, columns: &[ColumnChoice], existing: Option<&RuleLine
614 /// The "New rule" control and the form inside it. A `<details>` rather than709 /// The "New rule" control and the form inside it. A `<details>` rather than
615 /// anything script-driven, so a browser with no script can still open it and710 /// anything script-driven, so a browser with no script can still open it and
616 /// post the form.711 /// post the form.
617-async fn composer(cx: &Cx, columns: &[ColumnChoice], refusal: Option<&Refusal>, lang: Lang) -> Result {712+async fn composer(
713+ cx: &Cx,
714+ columns: &[ColumnChoice],
715+ refusal: Option<&Refusal>,
716+ lang: Lang,
717+) -> Result {
618 view! {718 view! {
619 cx =>719 cx =>
620 <details class="rule-new">720 <details class="rule-new">
@@ -626,7 +726,14 @@ async fn composer(cx: &Cx, columns: &[ColumnChoice], refusal: Option<&Refusal>,
626 726
627 /// One rule's row: the form in place of it when `editing`, its display727 /// One rule's row: the form in place of it when `editing`, its display
628 /// otherwise.728 /// otherwise.
629-async fn rule_row(cx: &Cx, rule: &RuleLine, columns: &[ColumnChoice], editing: bool, refusal: Option<&Refusal>, lang: Lang) -> Result {729+async fn rule_row(
730+ cx: &Cx,
731+ rule: &RuleLine,
732+ columns: &[ColumnChoice],
733+ editing: bool,
734+ refusal: Option<&Refusal>,
735+ lang: Lang,
736+) -> Result {
630 if editing {737 if editing {
631 return view! {738 return view! {
632 cx =>739 cx =>
@@ -636,14 +743,30 @@ async fn rule_row(cx: &Cx, rule: &RuleLine, columns: &[ColumnChoice], editing: b
636 };743 };
637 }744 }
638 745
639- let row_class = if rule.enabled { "rule-row" } else { "rule-row rule-row-off" };746+ let row_class = if rule.enabled {
640- let switch_class = if rule.enabled { "rule-switch rule-switch-on" } else { "rule-switch" };747+ "rule-row"
641- let switch_label = if rule.enabled { t(lang, Key::SwitchRuleOff) } else { t(lang, Key::SwitchRuleOn) };748+ } else {
749+ "rule-row rule-row-off"
750+ };
751+ let switch_class = if rule.enabled {
752+ "rule-switch rule-switch-on"
753+ } else {
754+ "rule-switch"
755+ };
756+ let switch_label = if rule.enabled {
757+ t(lang, Key::SwitchRuleOff)
758+ } else {
759+ t(lang, Key::SwitchRuleOn)
760+ };
642 let stamp = rule761 let stamp = rule
643 .last_sent762 .last_sent
644 .as_ref()763 .as_ref()
645 .map(|moment| crate::i18n::last_sent_label(lang, moment))764 .map(|moment| crate::i18n::last_sent_label(lang, moment))
646- .or_else(|| rule.last_fired.as_ref().map(|moment| crate::i18n::last_fired_label(lang, moment)))765+ .or_else(|| {
766+ rule.last_fired
767+ .as_ref()
768+ .map(|moment| crate::i18n::last_fired_label(lang, moment))
769+ })
647 .unwrap_or_else(|| t(lang, Key::NeverFired).to_string());770 .unwrap_or_else(|| t(lang, Key::NeverFired).to_string());
648 771
649 view! {772 view! {
@@ -717,7 +840,7 @@ async fn rules_page(cx: &Cx) -> Result {
717 </a>840 </a>
718 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Rules, lang).await?)841 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Rules, lang).await?)
719 <div class="spacer"></div>842 <div class="spacer"></div>
720- (crate::layout::user_menu(cx, &user.display_name, &user.email, user.role, lang).await?)843+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?)
721 </header>844 </header>
722 845
723 <div class="settings-shell">846 <div class="settings-shell">
crates/izlek-web/src/server.rsmodified+42 -8
@@ -86,7 +86,11 @@ impl Mail {
86 /// rehydrates it and lets the engine decide whether any rule owes a mail.86 /// rehydrates it and lets the engine decide whether any rule owes a mail.
87 /// `store` is the same store the request already wrote through — the87 /// `store` is the same store the request already wrote through — the
88 /// engine has no public handle back to it, so the caller carries it.88 /// engine has no public handle back to it, so the caller carries it.
89- pub fn after_activity(&self, store: std::sync::Arc<dyn izlek_core::store::Store>, activity_id: String) {89+ pub fn after_activity(
90+ &self,
91+ store: std::sync::Arc<dyn izlek_core::store::Store>,
92+ activity_id: String,
93+ ) {
90 let Some(engine) = self.0.clone() else {94 let Some(engine) = self.0.clone() else {
91 return;95 return;
92 };96 };
@@ -149,7 +153,9 @@ impl Mail {
149 /// The engine for this request, or a silent one when the router was built153 /// The engine for this request, or a silent one when the router was built
150 /// without an engine at all.154 /// without an engine at all.
151 pub fn mail(cx: &Cx) -> Mail {155 pub fn mail(cx: &Cx) -> Mail {
152- try_app_context::<Mail>(cx).cloned().unwrap_or_else(Mail::silent)156+ try_app_context::<Mail>(cx)
157+ .cloned()
158+ .unwrap_or_else(Mail::silent)
153 }159 }
154 160
155 /// The application cookie jar, with the attributes every Izlek cookie wants.161 /// The application cookie jar, with the attributes every Izlek cookie wants.
@@ -163,7 +169,9 @@ fn app_cookies(cx: &Cx) -> impl Cookies {
163 169
164 /// The cookie value this request presented, if it presented one.170 /// The cookie value this request presented, if it presented one.
165 pub fn presented_session(cx: &Cx) -> Option<String> {171 pub fn presented_session(cx: &Cx) -> Option<String> {
166- cookies(cx).get(SESSION_COOKIE).map(|c| c.value().to_string())172+ cookies(cx)
173+ .get(SESSION_COOKIE)
174+ .map(|c| c.value().to_string())
167 }175 }
168 176
169 /// A stable-enough label for the client, for rate limiting. A proxy header is177 /// A stable-enough label for the client, for rate limiting. A proxy header is
@@ -332,6 +340,8 @@ pub enum Refusal {
332 FileTooBig,340 FileTooBig,
333 /// The name does not end in one of the extensions the admin allows.341 /// The name does not end in one of the extensions the admin allows.
334 FileTypeNotAllowed,342 FileTypeNotAllowed,
343+ /// The bytes uploaded as a profile photo do not sniff as an image.
344+ NotAnImage,
335 /// A rule with no subject line: the mail it sends would arrive blank.345 /// A rule with no subject line: the mail it sends would arrive blank.
336 EmptySubject,346 EmptySubject,
337 /// The date field did not hold a date.347 /// The date field did not hold a date.
@@ -382,6 +392,7 @@ impl Refusal {
382 Refusal::FileTypeNotAllowed => {392 Refusal::FileTypeNotAllowed => {
383 "That kind of file is not on this workspace's allowed list.".to_string()393 "That kind of file is not on this workspace's allowed list.".to_string()
384 }394 }
395+ Refusal::NotAnImage => "That is not an image.".to_string(),
385 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),396 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
386 Refusal::BadDeadline => "That is not a date.".to_string(),397 Refusal::BadDeadline => "That is not a date.".to_string(),
387 Refusal::Cycle => "That link would put this task behind itself.".to_string(),398 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
@@ -410,6 +421,7 @@ impl Refusal {
410 Refusal::FileTypeNotAllowed => {421 Refusal::FileTypeNotAllowed => {
411 "Bu dosya türü bu çalışma alanının izin verdiği listede değil.".to_string()422 "Bu dosya türü bu çalışma alanının izin verdiği listede değil.".to_string()
412 }423 }
424+ Refusal::NotAnImage => "Bu bir resim değil.".to_string(),
413 Refusal::BadDeadline => "Bu bir tarih değil.".to_string(),425 Refusal::BadDeadline => "Bu bir tarih değil.".to_string(),
414 Refusal::Cycle => "Bu bağlantı görevi kendi arkasına koyar.".to_string(),426 Refusal::Cycle => "Bu bağlantı görevi kendi arkasına koyar.".to_string(),
415 Refusal::MovedAlready => "Bu kartı başka biri zaten taşıdı.".to_string(),427 Refusal::MovedAlready => "Bu kartı başka biri zaten taşıdı.".to_string(),
@@ -479,6 +491,7 @@ impl Refusal {
479 "no-file" => Refusal::NoFile,491 "no-file" => Refusal::NoFile,
480 "file-too-big" => Refusal::FileTooBig,492 "file-too-big" => Refusal::FileTooBig,
481 "file-type" => Refusal::FileTypeNotAllowed,493 "file-type" => Refusal::FileTypeNotAllowed,
494+ "not-an-image" => Refusal::NotAnImage,
482 "empty-subject" => Refusal::EmptySubject,495 "empty-subject" => Refusal::EmptySubject,
483 "bad-deadline" => Refusal::BadDeadline,496 "bad-deadline" => Refusal::BadDeadline,
484 "cycle" => Refusal::Cycle,497 "cycle" => Refusal::Cycle,
@@ -529,6 +542,7 @@ impl Refusal {
529 Refusal::NoFile => "no-file",542 Refusal::NoFile => "no-file",
530 Refusal::FileTooBig => "file-too-big",543 Refusal::FileTooBig => "file-too-big",
531 Refusal::FileTypeNotAllowed => "file-type",544 Refusal::FileTypeNotAllowed => "file-type",
545+ Refusal::NotAnImage => "not-an-image",
532 Refusal::EmptySubject => "empty-subject",546 Refusal::EmptySubject => "empty-subject",
533 Refusal::BadDeadline => "bad-deadline",547 Refusal::BadDeadline => "bad-deadline",
534 Refusal::Cycle => "cycle",548 Refusal::Cycle => "cycle",
@@ -601,7 +615,11 @@ pub fn refusal_of(cx: &Cx, call: &str) -> Option<Refusal> {
601 /// checks for is `SEE_OTHER` — the guard's three conditions are otherwise615 /// checks for is `SEE_OTHER` — the guard's three conditions are otherwise
602 /// unchanged.616 /// unchanged.
603 #[topcoat::router::layer("/api")]617 #[topcoat::router::layer("/api")]
604-async fn carry_refusal_on_redirect(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {618+async fn carry_refusal_on_redirect(
619+ cx: &Cx,
620+ body: Body,
621+ next: Next<'_>,
622+) -> topcoat::Result<Response> {
605 // A form post from a browser asks for a page back. A server-function call623 // A form post from a browser asks for a page back. A server-function call
606 // from the hydrated bundle does not.624 // from the hydrated bundle does not.
607 let wants_page = headers(cx)625 let wants_page = headers(cx)
@@ -626,8 +644,14 @@ async fn carry_refusal_on_redirect(cx: &Cx, body: Body, next: Next<'_>) -> topco
626 let Ok(bytes) = to_bytes(body, 64 * 1024).await else {644 let Ok(bytes) = to_bytes(body, 64 * 1024).await else {
627 return Ok(Response::from_parts(parts, Body::empty()));645 return Ok(Response::from_parts(parts, Body::empty()));
628 };646 };
629- let refusal = serde_json::from_slice::<Option<Refusal>>(&bytes).ok().flatten();647+ let refusal = serde_json::from_slice::<Option<Refusal>>(&bytes)
630- if let Some(location) = parts.headers.get(header::LOCATION).and_then(|v| v.to_str().ok()) {648+ .ok()
649+ .flatten();
650+ if let Some(location) = parts
651+ .headers
652+ .get(header::LOCATION)
653+ .and_then(|v| v.to_str().ok())
654+ {
631 let rewritten = match refusal {655 let rewritten = match refusal {
632 Some(refusal) => carrying(location, refusal.code(), &called),656 Some(refusal) => carrying(location, refusal.code(), &called),
633 None => Some(same_origin(location).to_string()),657 None => Some(same_origin(location).to_string()),
@@ -825,7 +849,11 @@ mod refusal_of_tests {
825 use topcoat::context::CxTestBuilder;849 use topcoat::context::CxTestBuilder;
826 850
827 fn cx_at(uri: &str) -> Cx {851 fn cx_at(uri: &str) -> Cx {
828- let (parts, ()) = http::Request::builder().uri(uri).body(()).unwrap().into_parts();852+ let (parts, ()) = http::Request::builder()
853+ .uri(uri)
854+ .body(())
855+ .unwrap()
856+ .into_parts();
829 CxTestBuilder::new().request_context(parts).build()857 CxTestBuilder::new().request_context(parts).build()
830 }858 }
831 859
@@ -906,7 +934,13 @@ mod session_cookie_tests {
906 let set = set_cookie_headers(&cx);934 let set = set_cookie_headers(&cx);
907 assert_eq!(set.len(), 1);935 assert_eq!(set.len(), 1);
908 assert!(set[0].starts_with("izlek_session=tok123;"), "{}", set[0]);936 assert!(set[0].starts_with("izlek_session=tok123;"), "{}", set[0]);
909- for attr in ["Path=/", "Secure", "HttpOnly", "SameSite=Lax", "Max-Age=1209600"] {937+ for attr in [
938+ "Path=/",
939+ "Secure",
940+ "HttpOnly",
941+ "SameSite=Lax",
942+ "Max-Age=1209600",
943+ ] {
910 assert!(set[0].contains(attr), "{} missing {attr}", set[0]);944 assert!(set[0].contains(attr), "{} missing {attr}", set[0]);
911 }945 }
912 }946 }
crates/izlek-web/src/settings.rsmodified+146 -40
@@ -171,7 +171,11 @@ mod codec_tests {
171 /// A 303 to `/settings`, with `query` appended.171 /// A 303 to `/settings`, with `query` appended.
172 fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec<u8>) {172 fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
173 let mut headers = HeaderMap::new();173 let mut headers = HeaderMap::new();
174- let location = if query.is_empty() { "/settings".to_string() } else { format!("/settings?{query}") };174+ let location = if query.is_empty() {
175+ "/settings".to_string()
176+ } else {
177+ format!("/settings?{query}")
178+ };
175 if let Ok(value) = HeaderValue::from_str(&location) {179 if let Ok(value) = HeaderValue::from_str(&location) {
176 headers.insert(header::LOCATION, value);180 headers.insert(header::LOCATION, value);
177 }181 }
@@ -181,7 +185,10 @@ fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
181 /// Where a save lands: back on Settings, with the refusal (if any) on the185 /// Where a save lands: back on Settings, with the refusal (if any) on the
182 /// query the same way `files.rs`'s upload carries one, or `saved=<call>`186 /// query the same way `files.rs`'s upload carries one, or `saved=<call>`
183 /// when there was nothing to refuse.187 /// when there was nothing to refuse.
184-fn saved_or_refused(call: &str, refusal: Option<Refusal>) -> (StatusCode, HeaderMap, Vec<u8>) {188+pub(crate) fn saved_or_refused(
189+ call: &str,
190+ refusal: Option<Refusal>,
191+) -> (StatusCode, HeaderMap, Vec<u8>) {
185 match refusal {192 match refusal {
186 // `BadSender`'s code collapses six different complaints into one193 // `BadSender`'s code collapses six different complaints into one
187 // generic "bad-sender"; the sentence save time actually wrote rides194 // generic "bad-sender"; the sentence save time actually wrote rides
@@ -224,18 +231,16 @@ fn qsdecode(text: &str) -> String {
224 out.push(b' ');231 out.push(b' ');
225 i += 1;232 i += 1;
226 }233 }
227- b'%' if i + 2 < bytes.len() => {234+ b'%' if i + 2 < bytes.len() => match u8::from_str_radix(&text[i + 1..i + 3], 16) {
228- match u8::from_str_radix(&text[i + 1..i + 3], 16) {235+ Ok(byte) => {
229- Ok(byte) => {236+ out.push(byte);
230- out.push(byte);237+ i += 3;
231- i += 3;
232- }
233- Err(_) => {
234- out.push(b'%');
235- i += 1;
236- }
237 }238 }
238- }239+ Err(_) => {
240+ out.push(b'%');
241+ i += 1;
242+ }
243+ },
239 b => {244 b => {
240 out.push(b);245 out.push(b);
241 i += 1;246 i += 1;
@@ -262,7 +267,10 @@ struct SaveLimitsForm {
262 /// checked against, so a type that is not a plain extension has no business267 /// checked against, so a type that is not a plain extension has no business
263 /// being stored as one.268 /// being stored as one.
264 #[route(POST "/api/save_limits")]269 #[route(POST "/api/save_limits")]
265-async fn save_limits(cx: &Cx, Form(input): Form<SaveLimitsForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {270+async fn save_limits(
271+ cx: &Cx,
272+ Form(input): Form<SaveLimitsForm>,
273+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
266 let admin = match require_admin(cx).await {274 let admin = match require_admin(cx).await {
267 Ok(admin) => admin,275 Ok(admin) => admin,
268 Err(refusal) => return Ok(saved_or_refused("save_limits", Some(refusal))),276 Err(refusal) => return Ok(saved_or_refused("save_limits", Some(refusal))),
@@ -319,7 +327,10 @@ struct SaveSenderForm {
319 /// half-filled sender is not a configuration — it is a mail nobody receives327 /// half-filled sender is not a configuration — it is a mail nobody receives
320 /// and a ledger nobody reads.328 /// and a ledger nobody reads.
321 #[route(POST "/api/save_sender")]329 #[route(POST "/api/save_sender")]
322-async fn save_sender(cx: &Cx, Form(input): Form<SaveSenderForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {330+async fn save_sender(
331+ cx: &Cx,
332+ Form(input): Form<SaveSenderForm>,
333+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
323 let admin = match require_admin(cx).await {334 let admin = match require_admin(cx).await {
324 Ok(admin) => admin,335 Ok(admin) => admin,
325 Err(refusal) => return Ok(saved_or_refused("save_sender", Some(refusal))),336 Err(refusal) => return Ok(saved_or_refused("save_sender", Some(refusal))),
@@ -417,7 +428,10 @@ async fn send_test_mail(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
417 let Some(outcome) = mail(cx).test(&admin.email).await else {428 let Some(outcome) = mail(cx).test(&admin.email).await else {
418 // No engine in this process at all. Nothing sends here, and saying so429 // No engine in this process at all. Nothing sends here, and saying so
419 // beats writing down a failure the settings did not cause.430 // beats writing down a failure the settings did not cause.
420- return Ok(saved_or_refused("send_test_mail", Some(Refusal::Unavailable)));431+ return Ok(saved_or_refused(
432+ "send_test_mail",
433+ Some(Refusal::Unavailable),
434+ ));
421 };435 };
422 436
423 let at = time::OffsetDateTime::now_utc();437 let at = time::OffsetDateTime::now_utc();
@@ -437,7 +451,10 @@ async fn send_test_mail(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
437 };451 };
438 if let Err(problem) = store.record_sender_test(&admin.workspace_id, test).await {452 if let Err(problem) = store.record_sender_test(&admin.workspace_id, test).await {
439 eprintln!("store error: {problem}");453 eprintln!("store error: {problem}");
440- return Ok(saved_or_refused("send_test_mail", Some(Refusal::Unavailable)));454+ return Ok(saved_or_refused(
455+ "send_test_mail",
456+ Some(Refusal::Unavailable),
457+ ));
441 }458 }
442 Ok(saved_or_refused("send_test_mail", None))459 Ok(saved_or_refused("send_test_mail", None))
443 }460 }
@@ -480,7 +497,11 @@ fn zone_options() -> Vec<String> {
480 if hour == 0 {497 if hour == 0 {
481 "UTC".to_string()498 "UTC".to_string()
482 } else {499 } else {
483- format!("UTC{}{:02}:00", if hour > 0 { "+" } else { "-" }, hour.abs())500+ format!(
501+ "UTC{}{:02}:00",
502+ if hour > 0 { "+" } else { "-" },
503+ hour.abs()
504+ )
484 }505 }
485 })506 })
486 .collect()507 .collect()
@@ -490,7 +511,10 @@ fn zone_options() -> Vec<String> {
490 /// touches anybody else here: the id comes from the session, never from the511 /// touches anybody else here: the id comes from the session, never from the
491 /// form.512 /// form.
492 #[route(POST "/api/save_profile")]513 #[route(POST "/api/save_profile")]
493-async fn save_profile(cx: &Cx, Form(input): Form<SaveProfileForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {514+async fn save_profile(
515+ cx: &Cx,
516+ Form(input): Form<SaveProfileForm>,
517+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
494 let user = match require_user(cx).await {518 let user = match require_user(cx).await {
495 Ok(user) => user,519 Ok(user) => user,
496 Err(refusal) => return Ok(saved_or_refused("save_profile", Some(refusal))),520 Err(refusal) => return Ok(saved_or_refused("save_profile", Some(refusal))),
@@ -515,7 +539,10 @@ async fn save_profile(cx: &Cx, Form(input): Form<SaveProfileForm>) -> Result<(St
515 if !LANGUAGE_OPTIONS.contains(&language.as_str()) {539 if !LANGUAGE_OPTIONS.contains(&language.as_str()) {
516 return Ok(saved_or_refused("save_profile", Some(Refusal::BadLanguage)));540 return Ok(saved_or_refused("save_profile", Some(Refusal::BadLanguage)));
517 }541 }
518- let email = input.email.map(|e| e.trim().to_lowercase()).unwrap_or_else(|| user.email.clone());542+ let email = input
543+ .email
544+ .map(|e| e.trim().to_lowercase())
545+ .unwrap_or_else(|| user.email.clone());
519 if !is_address(&email) {546 if !is_address(&email) {
520 return Ok(saved_or_refused("save_profile", Some(Refusal::BadEmail)));547 return Ok(saved_or_refused("save_profile", Some(Refusal::BadEmail)));
521 }548 }
@@ -524,13 +551,25 @@ async fn save_profile(cx: &Cx, Form(input): Form<SaveProfileForm>) -> Result<(St
524 // Checked before anything is written: a taken email must refuse the whole551 // Checked before anything is written: a taken email must refuse the whole
525 // save, not leave the name/theme/language/timezone changes standing while552 // save, not leave the name/theme/language/timezone changes standing while
526 // only the email is turned away.553 // only the email is turned away.
527- if email != user.email && store.user_by_email(&user.workspace_id, &email).await?.is_some() {554+ if email != user.email
528- return Ok(saved_or_refused("save_profile", Some(Refusal::AddressTaken)));555+ && store
556+ .user_by_email(&user.workspace_id, &email)
557+ .await?
558+ .is_some()
559+ {
560+ return Ok(saved_or_refused(
561+ "save_profile",
562+ Some(Refusal::AddressTaken),
563+ ));
529 }564 }
530 let outcome = store565 let outcome = store
531- .set_profile(&user.id, &display_name, user.photo_path.as_deref())566+ .set_profile(&user.id, &display_name)
532 .await567 .await
533- .and(store.set_preferences(&user.id, &timezone, &theme, &language, &ui).await)568+ .and(
569+ store
570+ .set_preferences(&user.id, &timezone, &theme, &language, &ui)
571+ .await,
572+ )
534 .and(store.set_email(&user.id, &user.workspace_id, &email).await);573 .and(store.set_email(&user.id, &user.workspace_id, &email).await);
535 let refusal = match outcome {574 let refusal = match outcome {
536 Ok(()) => None,575 Ok(()) => None,
@@ -555,7 +594,10 @@ struct ResendLinkForm {
555 /// mailed address travels home on the redirect's query, the same way a594 /// mailed address travels home on the redirect's query, the same way a
556 /// refusal does.595 /// refusal does.
557 #[route(POST "/api/resend_link")]596 #[route(POST "/api/resend_link")]
558-async fn resend_link(cx: &Cx, Form(input): Form<ResendLinkForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {597+async fn resend_link(
598+ cx: &Cx,
599+ Form(input): Form<ResendLinkForm>,
600+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
559 let admin = match require_admin(cx).await {601 let admin = match require_admin(cx).await {
560 Ok(admin) => admin,602 Ok(admin) => admin,
561 Err(refusal) => return Ok(saved_or_refused("resend_link", Some(refusal))),603 Err(refusal) => return Ok(saved_or_refused("resend_link", Some(refusal))),
@@ -563,7 +605,10 @@ async fn resend_link(cx: &Cx, Form(input): Form<ResendLinkForm>) -> Result<(Stat
563 match accounts(cx).resend_invitation(&admin, &input.user_id).await {605 match accounts(cx).resend_invitation(&admin, &input.user_id).await {
564 Ok(invitation) => {606 Ok(invitation) => {
565 mail(cx).after_invite();607 mail(cx).after_invite();
566- Ok(redirect_to(&format!("mailed={}", encode_q(&invitation.user.email))))608+ Ok(redirect_to(&format!(
609+ "mailed={}",
610+ encode_q(&invitation.user.email)
611+ )))
567 }612 }
568 Err(error) => Ok(saved_or_refused("resend_link", Some(error.into()))),613 Err(error) => Ok(saved_or_refused("resend_link", Some(error.into()))),
569 }614 }
@@ -578,12 +623,18 @@ struct SetRoleForm {
578 /// Changes a member's role. Admin-only; the owner's row and the caller's own623 /// Changes a member's role. Admin-only; the owner's row and the caller's own
579 /// row are refused, checked in `Accounts::set_role`.624 /// row are refused, checked in `Accounts::set_role`.
580 #[route(POST "/api/set_role")]625 #[route(POST "/api/set_role")]
581-async fn set_role(cx: &Cx, Form(input): Form<SetRoleForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {626+async fn set_role(
627+ cx: &Cx,
628+ Form(input): Form<SetRoleForm>,
629+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
582 let admin = match require_admin(cx).await {630 let admin = match require_admin(cx).await {
583 Ok(admin) => admin,631 Ok(admin) => admin,
584 Err(refusal) => return Ok(saved_or_refused("set_role", Some(refusal))),632 Err(refusal) => return Ok(saved_or_refused("set_role", Some(refusal))),
585 };633 };
586- match accounts(cx).set_role(&admin, &input.user_id, input.role).await {634+ match accounts(cx)
635+ .set_role(&admin, &input.user_id, input.role)
636+ .await
637+ {
587 Ok(()) => Ok(saved_or_refused("set_role", None)),638 Ok(()) => Ok(saved_or_refused("set_role", None)),
588 Err(error) => Ok(saved_or_refused("set_role", Some(error.into()))),639 Err(error) => Ok(saved_or_refused("set_role", Some(error.into()))),
589 }640 }
@@ -600,6 +651,7 @@ async fn set_role(cx: &Cx, Form(input): Form<SetRoleForm>) -> Result<(StatusCode
600 struct Member {651 struct Member {
601 id: String,652 id: String,
602 display_name: String,653 display_name: String,
654+ has_photo: bool,
603 email: String,655 email: String,
604 role: izlek_core::Role,656 role: izlek_core::Role,
605 has_password: bool,657 has_password: bool,
@@ -627,6 +679,7 @@ async fn members_now(cx: &Cx, asking: &User) -> Result<Vec<Member>> {
627 is_owner: owner.as_deref() == Some(user.id.as_str()),679 is_owner: owner.as_deref() == Some(user.id.as_str()),
628 id: user.id,680 id: user.id,
629 display_name: user.display_name,681 display_name: user.display_name,
682+ has_photo: user.has_photo,
630 email: user.email,683 email: user.email,
631 role: user.role,684 role: user.role,
632 })685 })
@@ -691,7 +744,10 @@ async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result<Sender> {
691 },744 },
692 Some(workspace) => Sender {745 Some(workspace) => Sender {
693 host: workspace.smtp_host.unwrap_or_default(),746 host: workspace.smtp_host.unwrap_or_default(),
694- port: workspace.smtp_port.and_then(|p| u16::try_from(p).ok()).unwrap_or(587),747+ port: workspace
748+ .smtp_port
749+ .and_then(|p| u16::try_from(p).ok())
750+ .unwrap_or(587),
695 username: workspace.smtp_username.unwrap_or_default(),751 username: workspace.smtp_username.unwrap_or_default(),
696 from_name: workspace.smtp_from_name.unwrap_or_default(),752 from_name: workspace.smtp_from_name.unwrap_or_default(),
697 from_address: workspace.smtp_from_address.unwrap_or_default(),753 from_address: workspace.smtp_from_address.unwrap_or_default(),
@@ -713,7 +769,9 @@ fn call_state<'q>(query: &'q str, call: &str) -> (Option<Refusal>, bool) {
713 let mut saved = false;769 let mut saved = false;
714 let mut why = None;770 let mut why = None;
715 for pair in query.split('&') {771 for pair in query.split('&') {
716- let Some((key, value)) = pair.split_once('=') else { continue };772+ let Some((key, value)) = pair.split_once('=') else {
773+ continue;
774+ };
717 match key {775 match key {
718 "refusal" => refusal_code = Some(value),776 "refusal" => refusal_code = Some(value),
719 "on" => on = Some(value),777 "on" => on = Some(value),
@@ -723,12 +781,14 @@ fn call_state<'q>(query: &'q str, call: &str) -> (Option<Refusal>, bool) {
723 }781 }
724 }782 }
725 let refusal = if on == Some(call) {783 let refusal = if on == Some(call) {
726- refusal_code.and_then(Refusal::from_code).map(|refusal| match (refusal, why) {784+ refusal_code
727- // The generic "bad-sender" fallback is what a tampered or absent785+ .and_then(Refusal::from_code)
728- // `why` gets; a real one carries save time's own sentence.786+ .map(|refusal| match (refusal, why) {
729- (Refusal::BadSender(_), Some(why)) => Refusal::BadSender(qsdecode(why)),787+ // The generic "bad-sender" fallback is what a tampered or absent
730- (refusal, _) => refusal,788+ // `why` gets; a real one carries save time's own sentence.
731- })789+ (Refusal::BadSender(_), Some(why)) => Refusal::BadSender(qsdecode(why)),
790+ (refusal, _) => refusal,
791+ })
732 } else {792 } else {
733 None793 None
734 };794 };
@@ -736,7 +796,11 @@ fn call_state<'q>(query: &'q str, call: &str) -> (Option<Refusal>, bool) {
736 }796 }
737 797
738 fn query_value<'q>(query: &'q str, key: &str) -> Option<&'q str> {798 fn query_value<'q>(query: &'q str, key: &str) -> Option<&'q str> {
739- query.split('&').find_map(|pair| pair.split_once('=').filter(|(k, _)| *k == key).map(|(_, v)| v))799+ query.split('&').find_map(|pair| {
800+ pair.split_once('=')
801+ .filter(|(k, _)| *k == key)
802+ .map(|(_, v)| v)
803+ })
740 }804 }
741 805
742 /// The settings screen.806 /// The settings screen.
@@ -760,16 +824,27 @@ async fn settings_page(cx: &Cx) -> Result {
760 let query = topcoat::router::request::uri(cx).query().unwrap_or("");824 let query = topcoat::router::request::uri(cx).query().unwrap_or("");
761 825
762 let zone = izlek_core::detail::parse_zone(&user.timezone);826 let zone = izlek_core::detail::parse_zone(&user.timezone);
763- let sender = if administers { Some(sender_now(cx, zone).await?) } else { None };827+ let sender = if administers {
828+ Some(sender_now(cx, zone).await?)
829+ } else {
830+ None
831+ };
764 let (limits, allowed_types) = if administers {832 let (limits, allowed_types) = if administers {
765 let (attachment, photo, types) = limits_now(cx, &user.workspace_id).await?;833 let (attachment, photo, types) = limits_now(cx, &user.workspace_id).await?;
766 (Some((attachment, photo)), types)834 (Some((attachment, photo)), types)
767 } else {835 } else {
768 (None, Vec::new())836 (None, Vec::new())
769 };837 };
770- let members = if administers { Some(members_now(cx, &user).await?) } else { None };838+ let members = if administers {
839+ Some(members_now(cx, &user).await?)
840+ } else {
841+ None
842+ };
771 843
772 let (profile_refusal, profile_saved) = call_state(query, "save_profile");844 let (profile_refusal, profile_saved) = call_state(query, "save_profile");
845+ let (photo_refusal, photo_saved) = call_state(query, "profile_photo");
846+ let (photo_delete_refusal, _) = call_state(query, "delete_profile_photo");
847+ let photo_refusal = photo_refusal.or(photo_delete_refusal);
773 let (sender_refusal, sender_saved) = call_state(query, "save_sender");848 let (sender_refusal, sender_saved) = call_state(query, "save_sender");
774 let (test_refusal, _) = call_state(query, "send_test_mail");849 let (test_refusal, _) = call_state(query, "send_test_mail");
775 let (limits_refusal, limits_saved) = call_state(query, "save_limits");850 let (limits_refusal, limits_saved) = call_state(query, "save_limits");
@@ -788,7 +863,7 @@ async fn settings_page(cx: &Cx) -> Result {
788 </a>863 </a>
789 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Settings, lang).await?)864 (crate::layout::topbar_nav(cx, crate::layout::NavPage::Settings, lang).await?)
790 <div class="spacer"></div>865 <div class="spacer"></div>
791- (crate::layout::user_menu(cx, &user.display_name, &user.email, user.role, lang).await?)866+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?)
792 </header>867 </header>
793 868
794 <div class="settings-shell">869 <div class="settings-shell">
@@ -865,6 +940,31 @@ async fn settings_page(cx: &Cx) -> Result {
865 <button class="primary" type="submit">(t(lang, Key::Save))</button>940 <button class="primary" type="submit">(t(lang, Key::Save))</button>
866 </div>941 </div>
867 </form>942 </form>
943+ <form class="panel-body photo-form" method="post" action="/api/profile_photo" enctype="multipart/form-data">
944+ <span class="field-label">(t(lang, Key::Picture))</span>
945+ <div class="photo-row">
946+ (crate::layout::avatar(cx, &izlek_core::board::Person {
947+ id: user.id.clone(),
948+ display_name: user.display_name.clone(),
949+ has_photo: user.has_photo,
950+ }, "avatar-lg").await?)
951+ <label class="field-box file-upload-box">
952+ <span class="field-text file-upload-name">(t(lang, Key::Picture))</span>
953+ <input class="file-upload-input" type="file" name="file" accept="image/*" data-autosubmit="">
954+ </label>
955+ </div>
956+ if let Some(refusal) = &photo_refusal {
957+ <span class="field-error">(refusal.message_in(lang))</span>
958+ }
959+ if photo_saved {
960+ <span class="field-note">(t(lang, Key::Saved))</span>
961+ }
962+ </form>
963+ if user.has_photo {
964+ <form class="panel-body photo-form" method="post" action="/api/delete_profile_photo">
965+ <button class="quiet" type="submit">(t(lang, Key::Remove))</button>
966+ </form>
967+ }
868 </section>968 </section>
869 969
870 if let Some(sender) = &sender {970 if let Some(sender) = &sender {
@@ -1057,9 +1157,15 @@ async fn settings_page(cx: &Cx) -> Result {
1057 } else {1157 } else {
1058 t(lang, Key::ActiveStatus).to_string()1158 t(lang, Key::ActiveStatus).to_string()
1059 };1159 };
1160+ let member_person = izlek_core::board::Person {
1161+ id: member.id.clone(),
1162+ display_name: member.display_name.clone(),
1163+ has_photo: member.has_photo,
1164+ };
1060 <tr class="member-row">1165 <tr class="member-row">
1061 <td class="member-name">1166 <td class="member-name">
1062 <span class="member-name-row">1167 <span class="member-name-row">
1168+ (crate::layout::avatar(cx, &member_person, "avatar-sm").await?)
1063 (member.display_name.clone())1169 (member.display_name.clone())
1064 if member.is_you {1170 if member.is_you {
1065 <span class="member-you">(t(lang, Key::You))</span>1171 <span class="member-you">(t(lang, Key::You))</span>
crates/izlek-web/src/smtp.rsmodified+1 -1
@@ -19,8 +19,8 @@
19 19
20 use std::sync::Arc;20 use std::sync::Arc;
21 21
22-use izlek_core::store::Store;
23 use izlek_core::mail::{MailError, Mailer, Outgoing};22 use izlek_core::mail::{MailError, Mailer, Outgoing};
23+use izlek_core::store::Store;
24 use lettre::message::header::ContentType;24 use lettre::message::header::ContentType;
25 use lettre::transport::smtp::authentication::Credentials;25 use lettre::transport::smtp::authentication::Credentials;
26 use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};26 use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
crates/izlek-web/tests/http.rsmodified+1732 -314

Diff too large; view file

@@ -37,7 +37,10 @@ use ulid::Ulid;
37 /// looks beside `current_exe` and would miss it, so the path is given37 /// looks beside `current_exe` and would miss it, so the path is given
38 /// explicitly instead.38 /// explicitly instead.
39 fn asset_dir() -> PathBuf {39 fn asset_dir() -> PathBuf {
40- PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/assets"))40+ PathBuf::from(concat!(
41+ env!("CARGO_MANIFEST_DIR"),
42+ "/../../target/debug/assets"
43+ ))
41 }44 }
42 45
43 /// A throwaway workspace: its own database file and its own router.46 /// A throwaway workspace: its own database file and its own router.
@@ -59,9 +62,15 @@ impl App {
59 let accounts = Accounts::new(store.clone(), base_url);62 let accounts = Accounts::new(store.clone(), base_url);
60 let router = Router::builder()63 let router = Router::builder()
61 .discover()64 .discover()
62- .layer(BodyLimit::max(izlek_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024).at("/files"))65+ .layer(
66+ BodyLimit::max(izlek_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024)
67+ .at("/files"),
68+ )
63 .cookies()69 .cookies()
64- .assets(AssetBundle::load_dir(asset_dir()).expect("run `topcoat asset bundle` before the http suite"))70+ .assets(
71+ AssetBundle::load_dir(asset_dir())
72+ .expect("run `topcoat asset bundle` before the http suite"),
73+ )
65 .app_context(accounts)74 .app_context(accounts)
66 .app_context(mail)75 .app_context(mail)
67 .build();76 .build();
@@ -91,9 +100,15 @@ impl App {
91 let accounts = Accounts::new(store.clone(), "https://izlek.sh");100 let accounts = Accounts::new(store.clone(), "https://izlek.sh");
92 let router = Router::builder()101 let router = Router::builder()
93 .discover()102 .discover()
94- .layer(BodyLimit::max(izlek_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024).at("/files"))103+ .layer(
104+ BodyLimit::max(izlek_web::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024)
105+ .at("/files"),
106+ )
95 .cookies()107 .cookies()
96- .assets(AssetBundle::load_dir(asset_dir()).expect("run `topcoat asset bundle` before the http suite"))108+ .assets(
109+ AssetBundle::load_dir(asset_dir())
110+ .expect("run `topcoat asset bundle` before the http suite"),
111+ )
97 .app_context(accounts)112 .app_context(accounts)
98 .app_context(Mail::sending(engine))113 .app_context(Mail::sending(engine))
99 .build();114 .build();
@@ -104,7 +119,12 @@ impl App {
104 /// single-tenant, so there is no id to guess and no JSON endpoint needed119 /// single-tenant, so there is no id to guess and no JSON endpoint needed
105 /// just to hand it back.120 /// just to hand it back.
106 async fn workspace_id(&self) -> String {121 async fn workspace_id(&self) -> String {
107- self.store.workspace().await.unwrap().expect("no workspace yet").id122+ self.store
123+ .workspace()
124+ .await
125+ .unwrap()
126+ .expect("no workspace yet")
127+ .id
108 }128 }
109 129
110 /// Posts a form the way a hydrated caller does: `Accept: application/json`,130 /// Posts a form the way a hydrated caller does: `Accept: application/json`,
@@ -128,7 +148,10 @@ impl App {
128 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),148 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
129 );149 );
130 }150 }
131- let response = self.router.handle(request.body(Body::from(body)).unwrap()).await;151+ let response = self
152+ .router
153+ .handle(request.body(Body::from(body)).unwrap())
154+ .await;
132 Answer::from_response(response).await155 Answer::from_response(response).await
133 }156 }
134 157
@@ -159,7 +182,10 @@ impl App {
159 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),182 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
160 );183 );
161 }184 }
162- let response = self.router.handle(request.body(Body::from(body)).unwrap()).await;185+ let response = self
186+ .router
187+ .handle(request.body(Body::from(body)).unwrap())
188+ .await;
163 let mut answer = Answer::from_response(response).await;189 let mut answer = Answer::from_response(response).await;
164 answer.session = None;190 answer.session = None;
165 answer191 answer
@@ -199,20 +225,20 @@ impl App {
199 }225 }
200 body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());226 body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
201 227
202- let mut request = Request::builder()228+ let mut request = Request::builder().method("POST").uri(path).header(
203- .method("POST")229+ header::CONTENT_TYPE,
204- .uri(path)230+ format!("multipart/form-data; boundary={BOUNDARY}"),
205- .header(231+ );
206- header::CONTENT_TYPE,
207- format!("multipart/form-data; boundary={BOUNDARY}"),
208- );
209 if let Some(cookie) = cookie {232 if let Some(cookie) = cookie {
210 request = request.header(233 request = request.header(
211 header::COOKIE,234 header::COOKIE,
212 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),235 HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
213 );236 );
214 }237 }
215- let response = self.router.handle(request.body(Body::from(body)).unwrap()).await;238+ let response = self
239+ .router
240+ .handle(request.body(Body::from(body)).unwrap())
241+ .await;
216 let mut answer = Answer::from_response(response).await;242 let mut answer = Answer::from_response(response).await;
217 answer.session = None;243 answer.session = None;
218 answer244 answer
@@ -228,6 +254,22 @@ impl App {
228 /// Like `get`, but with a `Range` header, for exercising the254 /// Like `get`, but with a `Range` header, for exercising the
229 /// `/files/{id}` partial-content path.255 /// `/files/{id}` partial-content path.
230 async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: Option<&str>) -> Raw {256 async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: Option<&str>) -> Raw {
257+ self.get_with(path, cookie, range, None).await
258+ }
259+
260+ /// Like `get`, but with `If-None-Match`, for the `/photo/{user_id}`
261+ /// revalidate path.
262+ async fn get_with_if_none_match(&self, path: &str, cookie: Option<&str>, etag: &str) -> Raw {
263+ self.get_with(path, cookie, None, Some(etag)).await
264+ }
265+
266+ async fn get_with(
267+ &self,
268+ path: &str,
269+ cookie: Option<&str>,
270+ range: Option<&str>,
271+ if_none_match: Option<&str>,
272+ ) -> Raw {
231 let mut request = Request::builder().method("GET").uri(path);273 let mut request = Request::builder().method("GET").uri(path);
232 if let Some(cookie) = cookie {274 if let Some(cookie) = cookie {
233 request = request.header(275 request = request.header(
@@ -238,7 +280,13 @@ impl App {
238 if let Some(range) = range {280 if let Some(range) = range {
239 request = request.header(header::RANGE, range);281 request = request.header(header::RANGE, range);
240 }282 }
241- let response = self.router.handle(request.body(Body::empty()).unwrap()).await;283+ if let Some(if_none_match) = if_none_match {
284+ request = request.header(header::IF_NONE_MATCH, if_none_match);
285+ }
286+ let response = self
287+ .router
288+ .handle(request.body(Body::empty()).unwrap())
289+ .await;
242 let status = response.status();290 let status = response.status();
243 let content_type = response291 let content_type = response
244 .headers()292 .headers()
@@ -260,8 +308,24 @@ impl App {
260 .get(header::ACCEPT_RANGES)308 .get(header::ACCEPT_RANGES)
261 .and_then(|value| value.to_str().ok())309 .and_then(|value| value.to_str().ok())
262 .map(str::to_string);310 .map(str::to_string);
263- let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap().to_vec();311+ let etag = response
264- Raw { status, content_type, disposition, content_range, accept_ranges, bytes }312+ .headers()
313+ .get(header::ETAG)
314+ .and_then(|value| value.to_str().ok())
315+ .map(str::to_string);
316+ let bytes = to_bytes(response.into_body(), usize::MAX)
317+ .await
318+ .unwrap()
319+ .to_vec();
320+ Raw {
321+ status,
322+ content_type,
323+ disposition,
324+ content_range,
325+ accept_ranges,
326+ etag,
327+ bytes,
328+ }
265 }329 }
266 }330 }
267 331
@@ -279,6 +343,7 @@ struct Raw {
279 disposition: Option<String>,343 disposition: Option<String>,
280 content_range: Option<String>,344 content_range: Option<String>,
281 accept_ranges: Option<String>,345 accept_ranges: Option<String>,
346+ etag: Option<String>,
282 bytes: Vec<u8>,347 bytes: Vec<u8>,
283 }348 }
284 349
@@ -363,7 +428,10 @@ async fn sender_saved(app: &App, admin: &str) -> bool {
363 )428 )
364 .await;429 .await;
365 answer.status == StatusCode::SEE_OTHER430 answer.status == StatusCode::SEE_OTHER
366- && answer.location.as_deref().is_some_and(|location| !location.contains("refusal="))431+ && answer
432+ .location
433+ .as_deref()
434+ .is_some_and(|location| !location.contains("refusal="))
367 }435 }
368 436
369 /// Claims the workspace and returns the admin's session cookie.437 /// Claims the workspace and returns the admin's session cookie.
@@ -440,15 +508,30 @@ async fn invited(app: &App, admin: &str, email: &str, name: &str, role: Role) ->
440 /// server-rendered shard now), and the id is fixture setup, not the behavior508 /// server-rendered shard now), and the id is fixture setup, not the behavior
441 /// under test.509 /// under test.
442 async fn first_column(app: &App) -> String {510 async fn first_column(app: &App) -> String {
443- columns_of(app).await.into_iter().next().expect("no columns on a fresh board")511+ columns_of(app)
512+ .await
513+ .into_iter()
514+ .next()
515+ .expect("no columns on a fresh board")
444 }516 }
445 517
446 /// Every column id on the board, in order, read straight off the store — see518 /// Every column id on the board, in order, read straight off the store — see
447 /// [`first_column`] on why this bypasses HTTP.519 /// [`first_column`] on why this bypasses HTTP.
448 async fn columns_of(app: &App) -> Vec<String> {520 async fn columns_of(app: &App) -> Vec<String> {
449 let workspace_id = app.workspace_id().await;521 let workspace_id = app.workspace_id().await;
450- let board = app.store.board(&workspace_id).await.unwrap().expect("no board");522+ let board = app
451- app.store.columns(&board.id).await.unwrap().into_iter().map(|c| c.id).collect()523+ .store
524+ .board(&workspace_id)
525+ .await
526+ .unwrap()
527+ .expect("no board");
528+ app.store
529+ .columns(&board.id)
530+ .await
531+ .unwrap()
532+ .into_iter()
533+ .map(|c| c.id)
534+ .collect()
452 }535 }
453 536
454 /// Makes a task and hands back its id, read straight off the store — there is537 /// Makes a task and hands back its id, read straight off the store — there is
@@ -456,12 +539,19 @@ async fn columns_of(app: &App) -> Vec<String> {
456 /// server-rendered shard now); the mutation itself is still a real HTTP post.539 /// server-rendered shard now); the mutation itself is still a real HTTP post.
457 async fn a_task(app: &App, cookie: &str, column: &str, title: &str) -> String {540 async fn a_task(app: &App, cookie: &str, column: &str, title: &str) -> String {
458 let answer = app541 let answer = app
459- .post("/api/create_task", Some(cookie), &[("title", title), ("column_id", column)])542+ .post(
543+ "/api/create_task",
544+ Some(cookie),
545+ &[("title", title), ("column_id", column)],
546+ )
460 .await;547 .await;
461 assert_eq!(answer.body, "", "the task was refused: {}", answer.body);548 assert_eq!(answer.body, "", "the task was refused: {}", answer.body);
462 549
463 let workspace_id = app.workspace_id().await;550 let workspace_id = app.workspace_id().await;
464- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();551+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
552+ .await
553+ .unwrap()
554+ .unwrap();
465 board555 board
466 .columns556 .columns
467 .iter()557 .iter()
@@ -503,7 +593,11 @@ async fn adding_a_member_mails_them_the_link() {
503 .collect();593 .collect();
504 assert_eq!(invites.len(), 1, "{invites:?}");594 assert_eq!(invites.len(), 1, "{invites:?}");
505 assert!(595 assert!(
506- invites[0].body.as_deref().unwrap_or_default().contains("/join/"),596+ invites[0]
597+ .body
598+ .as_deref()
599+ .unwrap_or_default()
600+ .contains("/join/"),
507 "{:?}",601 "{:?}",
508 invites[0]602 invites[0]
509 );603 );
@@ -555,7 +649,13 @@ async fn a_resend_queues_another_mail() {
555 649
556 // `resend_link` has no hydrated action to answer with a value here: the650 // `resend_link` has no hydrated action to answer with a value here: the
557 // mailed address rides the redirect's query instead of a JSON body.651 // mailed address rides the redirect's query instead of a JSON body.
558- let resent = app.post("/api/resend_link", Some(&admin_cookie), &[("user_id", &sena_id)]).await;652+ let resent = app
653+ .post(
654+ "/api/resend_link",
655+ Some(&admin_cookie),
656+ &[("user_id", &sena_id)],
657+ )
658+ .await;
559 assert_eq!(resent.status, StatusCode::SEE_OTHER, "{}", resent.body);659 assert_eq!(resent.status, StatusCode::SEE_OTHER, "{}", resent.body);
560 let location = resent.location.expect("resend did not redirect");660 let location = resent.location.expect("resend did not redirect");
561 assert!(location.contains("mailed=sena%40izlek.sh"), "{location}");661 assert!(location.contains("mailed=sena%40izlek.sh"), "{location}");
@@ -585,16 +685,27 @@ async fn a_viewer_who_posts_to_create_task_anyway_is_refused() {
585 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);685 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
586 assert_eq!(answer.body, "");686 assert_eq!(answer.body, "");
587 assert!(687 assert!(
588- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=create_task"),688+ answer
689+ .location
690+ .as_deref()
691+ .unwrap_or_default()
692+ .contains("refusal=forbidden&on=create_task"),
589 "{:?}",693 "{:?}",
590 answer.location694 answer.location
591 );695 );
592 696
593 // And the refusal is not cosmetic: the board is still empty.697 // And the refusal is not cosmetic: the board is still empty.
594 let workspace_id = app.workspace_id().await;698 let workspace_id = app.workspace_id().await;
595- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();699+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
700+ .await
701+ .unwrap()
702+ .unwrap();
596 assert!(703 assert!(
597- board.columns.iter().flat_map(|c| &c.cards).all(|card| card.title != "Viewer should not get this"),704+ board
705+ .columns
706+ .iter()
707+ .flat_map(|c| &c.cards)
708+ .all(|card| card.title != "Viewer should not get this"),
598 "the refused task was written anyway"709 "the refused task was written anyway"
599 );710 );
600 }711 }
@@ -615,23 +726,37 @@ async fn a_member_may_create_a_task() {
615 .await;726 .await;
616 assert_eq!(answer.body, "");727 assert_eq!(answer.body, "");
617 assert!(728 assert!(
618- !answer.location.as_deref().unwrap_or_default().contains("refusal="),729+ !answer
730+ .location
731+ .as_deref()
732+ .unwrap_or_default()
733+ .contains("refusal="),
619 "a create that worked said it was refused: {:?}",734 "a create that worked said it was refused: {:?}",
620 answer.location735 answer.location
621 );736 );
622 737
623 let workspace_id = app.workspace_id().await;738 let workspace_id = app.workspace_id().await;
624- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();739+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
740+ .await
741+ .unwrap()
742+ .unwrap();
625 let card = board743 let card = board
626 .columns744 .columns
627 .iter()745 .iter()
628 .flat_map(|c| &c.cards)746 .flat_map(|c| &c.cards)
629 .find(|card| card.title == "Wire the deadline chip")747 .find(|card| card.title == "Wire the deadline chip")
630 .expect("new task is not on the board");748 .expect("new task is not on the board");
631- let tail = card.task_key.strip_prefix("DZ-").expect("key not shaped like DZ-<tail>");749+ let tail = card
632- assert!((5..=7).contains(&tail.len()), "key tail {tail} not 5..=7 chars");750+ .task_key
751+ .strip_prefix("DZ-")
752+ .expect("key not shaped like DZ-<tail>");
753+ assert!(
754+ (5..=7).contains(&tail.len()),
755+ "key tail {tail} not 5..=7 chars"
756+ );
633 assert!(757 assert!(
634- tail.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()),758+ tail.chars()
759+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()),
635 "key tail {tail} not uppercase alnum"760 "key tail {tail} not uppercase alnum"
636 );761 );
637 }762 }
@@ -679,14 +804,25 @@ async fn a_task_cannot_be_dropped_into_another_workspaces_column() {
679 .await;804 .await;
680 assert_eq!(answer.body, "");805 assert_eq!(answer.body, "");
681 assert!(806 assert!(
682- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=create_task"),807+ answer
808+ .location
809+ .as_deref()
810+ .unwrap_or_default()
811+ .contains("refusal=forbidden&on=create_task"),
683 "{:?}",812 "{:?}",
684 answer.location813 answer.location
685 );814 );
686 let workspace_id = app.workspace_id().await;815 let workspace_id = app.workspace_id().await;
687- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();816+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
817+ .await
818+ .unwrap()
819+ .unwrap();
688 assert!(820 assert!(
689- board.columns.iter().flat_map(|c| &c.cards).all(|card| card.title != "Wrong column"),821+ board
822+ .columns
823+ .iter()
824+ .flat_map(|c| &c.cards)
825+ .all(|card| card.title != "Wrong column"),
690 "the refused task was written anyway"826 "the refused task was written anyway"
691 );827 );
692 }828 }
@@ -698,17 +834,32 @@ async fn a_card_needs_a_title() {
698 let column = first_column(&app).await;834 let column = first_column(&app).await;
699 835
700 let answer = app836 let answer = app
701- .post("/api/create_task", Some(&admin), &[("title", " "), ("column_id", &column)])837+ .post(
838+ "/api/create_task",
839+ Some(&admin),
840+ &[("title", " "), ("column_id", &column)],
841+ )
702 .await;842 .await;
703 assert_eq!(answer.body, "");843 assert_eq!(answer.body, "");
704 assert!(844 assert!(
705- answer.location.as_deref().unwrap_or_default().contains("refusal=empty-title&on=create_task"),845+ answer
846+ .location
847+ .as_deref()
848+ .unwrap_or_default()
849+ .contains("refusal=empty-title&on=create_task"),
706 "{:?}",850 "{:?}",
707 answer.location851 answer.location
708 );852 );
709 let workspace_id = app.workspace_id().await;853 let workspace_id = app.workspace_id().await;
710- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();854+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
711- assert_eq!(board.columns.iter().flat_map(|c| &c.cards).count(), 0, "a blank title was stored anyway");855+ .await
856+ .unwrap()
857+ .unwrap();
858+ assert_eq!(
859+ board.columns.iter().flat_map(|c| &c.cards).count(),
860+ 0,
861+ "a blank title was stored anyway"
862+ );
712 }863 }
713 864
714 #[tokio::test]865 #[tokio::test]
@@ -721,7 +872,10 @@ async fn the_board_is_not_readable_without_a_session() {
721 // signed-out board page itself.872 // signed-out board page itself.
722 let raw = app.get("/", None).await;873 let raw = app.get("/", None).await;
723 let html = String::from_utf8_lossy(&raw.bytes);874 let html = String::from_utf8_lossy(&raw.bytes);
724- assert!(!html.contains("board-stage"), "a signed-out browser was shown the board: {html}");875+ assert!(
876+ !html.contains("board-stage"),
877+ "a signed-out browser was shown the board: {html}"
878+ );
725 }879 }
726 880
727 /// The sort control still posts as a plain `<select name=sort>` — `dropdown.rs`881 /// The sort control still posts as a plain `<select name=sort>` — `dropdown.rs`
@@ -734,17 +888,32 @@ async fn the_board_sort_control_keeps_its_hidden_select_and_gets_a_dropdown_trig
734 888
735 let page = app.get("/", Some(&admin)).await;889 let page = app.get("/", Some(&admin)).await;
736 let html = String::from_utf8_lossy(&page.bytes);890 let html = String::from_utf8_lossy(&page.bytes);
737- assert!(html.contains("select class=\"status-select\" name=\"sort\""), "{html}");891+ assert!(
892+ html.contains("select class=\"status-select\" name=\"sort\""),
893+ "{html}"
894+ );
738 // `dropdown.rs`'s script is what turns that hidden select into the895 // `dropdown.rs`'s script is what turns that hidden select into the
739 // house trigger + panel client-side; its presence is the page's only896 // house trigger + panel client-side; its presence is the page's only
740 // server-rendered proof the shell is wired in.897 // server-rendered proof the shell is wired in.
741- assert!(html.contains("dd-trigger"), "no dropdown script on the board page: {html}");898+ assert!(
899+ html.contains("dd-trigger"),
900+ "no dropdown script on the board page: {html}"
901+ );
742 // `root_layout` emits `layout.rs`'s Escape manager on every page; the902 // `root_layout` emits `layout.rs`'s Escape manager on every page; the
743 // registration below is proof the topbar `.user-menu` gets its close903 // registration below is proof the topbar `.user-menu` gets its close
744 // path on the board page too.904 // path on the board page too.
745- assert!(html.contains("window.__izlekEsc"), "no escape manager on the board page: {html}");905+ assert!(
746- assert!(html.contains("__izlekEsc.register(40"), "no escape script on the board page: {html}");906+ html.contains("window.__izlekEsc"),
747- assert!(html.contains("closest('.user-menu')"), "no user-menu close path on the board page: {html}");907+ "no escape manager on the board page: {html}"
908+ );
909+ assert!(
910+ html.contains("__izlekEsc.register(40"),
911+ "no escape script on the board page: {html}"
912+ );
913+ assert!(
914+ html.contains("closest('.user-menu')"),
915+ "no user-menu close path on the board page: {html}"
916+ );
748 }917 }
749 918
750 #[tokio::test]919 #[tokio::test]
@@ -766,7 +935,9 @@ async fn a_viewer_who_posts_a_comment_anyway_is_refused() {
766 assert_eq!(answer.body, "\"Forbidden\"");935 assert_eq!(answer.body, "\"Forbidden\"");
767 936
768 // The refusal is not cosmetic: nothing was written.937 // The refusal is not cosmetic: nothing was written.
769- let answer = app.post("/api/fetch_task", Some(&admin), &[("task_id", &task)]).await;938+ let answer = app
939+ .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
940+ .await;
770 assert!(941 assert!(
771 !answer.body.contains("Viewers cannot say this"),942 !answer.body.contains("Viewers cannot say this"),
772 "the refused comment was written anyway: {}",943 "the refused comment was written anyway: {}",
@@ -791,7 +962,9 @@ async fn a_member_may_comment_and_the_author_is_the_session() {
791 .await;962 .await;
792 assert_eq!(answer.body, "null", "a member was refused: {}", answer.body);963 assert_eq!(answer.body, "null", "a member was refused: {}", answer.body);
793 964
794- let answer = app.post("/api/fetch_task", Some(&admin), &[("task_id", &task)]).await;965+ let answer = app
966+ .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
967+ .await;
795 assert!(answer.body.contains("Picker is narrow on purpose"));968 assert!(answer.body.contains("Picker is narrow on purpose"));
796 assert!(969 assert!(
797 answer.body.contains("Kai Renner"),970 answer.body.contains("Kai Renner"),
@@ -812,16 +985,28 @@ async fn a_link_that_would_close_a_circle_is_refused_at_the_endpoint() {
812 .post(985 .post(
813 "/api/link_tasks",986 "/api/link_tasks",
814 Some(&admin),987 Some(&admin),
815- &[("task_id", &second), ("other_id", &first), ("direction", "blocked_by")],988+ &[
989+ ("task_id", &second),
990+ ("other_id", &first),
991+ ("direction", "blocked_by"),
992+ ],
816 )993 )
817 .await;994 .await;
818- assert_eq!(answer.body, "null", "the first link was refused: {}", answer.body);995+ assert_eq!(
996+ answer.body, "null",
997+ "the first link was refused: {}",
998+ answer.body
999+ );
819 1000
820 let answer = app1001 let answer = app
821 .post(1002 .post(
822 "/api/link_tasks",1003 "/api/link_tasks",
823 Some(&admin),1004 Some(&admin),
824- &[("task_id", &first), ("other_id", &second), ("direction", "blocked_by")],1005+ &[
1006+ ("task_id", &first),
1007+ ("other_id", &second),
1008+ ("direction", "blocked_by"),
1009+ ],
825 )1010 )
826 .await;1011 .await;
827 assert_eq!(answer.body, "\"Cycle\"");1012 assert_eq!(answer.body, "\"Cycle\"");
@@ -838,7 +1023,11 @@ async fn a_refusal_reaches_a_browser_with_no_script() {
838 app.post(1023 app.post(
839 "/api/link_tasks",1024 "/api/link_tasks",
840 Some(&admin),1025 Some(&admin),
841- &[("task_id", &second), ("other_id", &first), ("direction", "blocked_by")],1026+ &[
1027+ ("task_id", &second),
1028+ ("other_id", &first),
1029+ ("direction", "blocked_by"),
1030+ ],
842 )1031 )
843 .await;1032 .await;
844 1033
@@ -849,7 +1038,11 @@ async fn a_refusal_reaches_a_browser_with_no_script() {
849 "/api/link_tasks",1038 "/api/link_tasks",
850 Some(&admin),1039 Some(&admin),
851 &format!("http://izlek.test/?task={first}"),1040 &format!("http://izlek.test/?task={first}"),
852- &[("task_id", &first), ("other_id", &second), ("direction", "blocked_by")],1041+ &[
1042+ ("task_id", &first),
1043+ ("other_id", &second),
1044+ ("direction", "blocked_by"),
1045+ ],
853 )1046 )
854 .await;1047 .await;
855 assert_eq!(answer.status, StatusCode::SEE_OTHER);1048 assert_eq!(answer.status, StatusCode::SEE_OTHER);
@@ -877,12 +1070,19 @@ async fn a_call_that_was_not_refused_carries_nothing_back() {
877 "/api/link_tasks",1070 "/api/link_tasks",
878 Some(&admin),1071 Some(&admin),
879 "http://izlek.test/",1072 "http://izlek.test/",
880- &[("task_id", &second), ("other_id", &first), ("direction", "blocked_by")],1073+ &[
1074+ ("task_id", &second),
1075+ ("other_id", &first),
1076+ ("direction", "blocked_by"),
1077+ ],
881 )1078 )
882 .await;1079 .await;
883 assert_eq!(answer.status, StatusCode::SEE_OTHER);1080 assert_eq!(answer.status, StatusCode::SEE_OTHER);
884 let location = answer.location.expect("a redirect with nowhere to go");1081 let location = answer.location.expect("a redirect with nowhere to go");
885- assert!(!location.contains("refusal="), "a link that was made said it was refused: {location}");1082+ assert!(
1083+ !location.contains("refusal="),
1084+ "a link that was made said it was refused: {location}"
1085+ );
886 }1086 }
887 1087
888 #[tokio::test]1088 #[tokio::test]
@@ -891,7 +1091,11 @@ async fn a_task_id_from_nowhere_is_not_found() {
891 let admin = admin(&app).await;1091 let admin = admin(&app).await;
892 1092
893 let answer = app1093 let answer = app
894- .post("/api/fetch_task", Some(&admin), &[("task_id", "00000000-0000-0000-0000-000000000000")])1094+ .post(
1095+ "/api/fetch_task",
1096+ Some(&admin),
1097+ &[("task_id", "00000000-0000-0000-0000-000000000000")],
1098+ )
895 .await;1099 .await;
896 assert_eq!(answer.body, "{\"Err\":\"NotFound\"}");1100 assert_eq!(answer.body, "{\"Err\":\"NotFound\"}");
897 }1101 }
@@ -904,13 +1108,22 @@ async fn a_viewer_who_posts_a_delete_anyway_is_refused() {
904 let column = first_column(&app).await;1108 let column = first_column(&app).await;
905 let task = a_task(&app, &admin, &column, "Viewers cannot remove this").await;1109 let task = a_task(&app, &admin, &column, "Viewers cannot remove this").await;
906 1110
907- let answer = app.post("/api/delete_task", Some(&viewer), &[("task_id", &task)]).await;1111+ let answer = app
1112+ .post("/api/delete_task", Some(&viewer), &[("task_id", &task)])
1113+ .await;
908 assert_eq!(answer.body, "\"Forbidden\"");1114 assert_eq!(answer.body, "\"Forbidden\"");
909 1115
910 let workspace_id = app.workspace_id().await;1116 let workspace_id = app.workspace_id().await;
911- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();1117+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
1118+ .await
1119+ .unwrap()
1120+ .unwrap();
912 assert!(1121 assert!(
913- board.columns.iter().flat_map(|c| &c.cards).any(|card| card.title == "Viewers cannot remove this"),1122+ board
1123+ .columns
1124+ .iter()
1125+ .flat_map(|c| &c.cards)
1126+ .any(|card| card.title == "Viewers cannot remove this"),
914 "the refused delete happened anyway"1127 "the refused delete happened anyway"
915 );1128 );
916 }1129 }
@@ -931,7 +1144,11 @@ async fn deleting_the_task_the_modal_came_from_lands_on_the_board_not_the_dead_m
931 )1144 )
932 .await;1145 .await;
933 assert_eq!(answer.status, StatusCode::SEE_OTHER);1146 assert_eq!(answer.status, StatusCode::SEE_OTHER);
934- assert_eq!(answer.location.as_deref(), Some("/"), "a deleted task's modal should not reopen");1147+ assert_eq!(
1148+ answer.location.as_deref(),
1149+ Some("/"),
1150+ "a deleted task's modal should not reopen"
1151+ );
935 }1152 }
936 1153
937 #[tokio::test]1154 #[tokio::test]
@@ -943,25 +1160,53 @@ async fn a_member_may_delete_and_the_delete_is_soft() {
943 let task = a_task(&app, &admin, &column, "Mistyped in a hurry").await;1160 let task = a_task(&app, &admin, &column, "Mistyped in a hurry").await;
944 1161
945 // What it would cost is a read: it says so and writes nothing.1162 // What it would cost is a read: it says so and writes nothing.
946- let answer = app.post("/api/what_delete_costs", Some(&member), &[("task_id", &task)]).await;1163+ let answer = app
947- assert!(answer.body.contains("Mistyped in a hurry"), "{}", answer.body);1164+ .post(
1165+ "/api/what_delete_costs",
1166+ Some(&member),
1167+ &[("task_id", &task)],
1168+ )
1169+ .await;
1170+ assert!(
1171+ answer.body.contains("Mistyped in a hurry"),
1172+ "{}",
1173+ answer.body
1174+ );
948 let workspace_id = app.workspace_id().await;1175 let workspace_id = app.workspace_id().await;
949- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();1176+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
1177+ .await
1178+ .unwrap()
1179+ .unwrap();
950 assert!(1180 assert!(
951- board.columns.iter().flat_map(|c| &c.cards).any(|card| card.title == "Mistyped in a hurry"),1181+ board
1182+ .columns
1183+ .iter()
1184+ .flat_map(|c| &c.cards)
1185+ .any(|card| card.title == "Mistyped in a hurry"),
952 "asking cost deleted it"1186 "asking cost deleted it"
953 );1187 );
954 1188
955- let answer = app.post("/api/delete_task", Some(&member), &[("task_id", &task)]).await;1189+ let answer = app
1190+ .post("/api/delete_task", Some(&member), &[("task_id", &task)])
1191+ .await;
956 assert_eq!(answer.body, "null", "a member was refused: {}", answer.body);1192 assert_eq!(answer.body, "null", "a member was refused: {}", answer.body);
957 1193
958 // Gone from the board, and gone from the detail: soft is not visible.1194 // Gone from the board, and gone from the detail: soft is not visible.
959- let board = izlek_core::board::load(app.store.as_ref(), &workspace_id).await.unwrap().unwrap();1195+ let board = izlek_core::board::load(app.store.as_ref(), &workspace_id)
1196+ .await
1197+ .unwrap()
1198+ .unwrap();
960 assert!(1199 assert!(
961- board.columns.iter().flat_map(|c| &c.cards).all(|card| card.title != "Mistyped in a hurry"),1200+ board
1201+ .columns
1202+ .iter()
1203+ .flat_map(|c| &c.cards)
1204+ .all(|card| card.title != "Mistyped in a hurry"),
962 "the task is still on the board"1205 "the task is still on the board"
963 );1206 );
964- let answer = app.post("/api/fetch_task", Some(&admin), &[("task_id", &task)]).await;1207+ let answer = app
1208+ .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1209+ .await;
965 assert_eq!(answer.body, "{\"Err\":\"NotFound\"}");1210 assert_eq!(answer.body, "{\"Err\":\"NotFound\"}");
966 }1211 }
967 1212
@@ -977,20 +1222,30 @@ async fn a_viewer_who_posts_a_move_anyway_is_refused() {
977 .post(1222 .post(
978 "/api/move_card",1223 "/api/move_card",
979 Some(&viewer),1224 Some(&viewer),
980- &[("task_id", &task), ("from_column_id", &columns[0]), ("to_column_id", &columns[1])],1225+ &[
1226+ ("task_id", &task),
1227+ ("from_column_id", &columns[0]),
1228+ ("to_column_id", &columns[1]),
1229+ ],
981 )1230 )
982 .await;1231 .await;
983 1232
984 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);1233 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
985 assert_eq!(answer.body, "");1234 assert_eq!(answer.body, "");
986 assert!(1235 assert!(
987- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=move_card"),1236+ answer
1237+ .location
1238+ .as_deref()
1239+ .unwrap_or_default()
1240+ .contains("refusal=forbidden&on=move_card"),
988 "{:?}",1241 "{:?}",
989 answer.location1242 answer.location
990 );1243 );
991 1244
992 // And nothing moved: the refusal is in the handler, not in the drawing.1245 // And nothing moved: the refusal is in the handler, not in the drawing.
993- let answer = app.post("/api/fetch_task", Some(&admin), &[("task_id", &task)]).await;1246+ let answer = app
1247+ .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1248+ .await;
994 assert!(1249 assert!(
995 answer.body.contains(&columns[0]),1250 answer.body.contains(&columns[0]),
996 "the refused move happened anyway: {}",1251 "the refused move happened anyway: {}",
@@ -1010,17 +1265,27 @@ async fn a_member_may_move_a_card() {
1010 .post(1265 .post(
1011 "/api/move_card",1266 "/api/move_card",
1012 Some(&member),1267 Some(&member),
1013- &[("task_id", &task), ("from_column_id", &columns[0]), ("to_column_id", &columns[1])],1268+ &[
1269+ ("task_id", &task),
1270+ ("from_column_id", &columns[0]),
1271+ ("to_column_id", &columns[1]),
1272+ ],
1014 )1273 )
1015 .await;1274 .await;
1016 assert_eq!(answer.body, "");1275 assert_eq!(answer.body, "");
1017 assert!(1276 assert!(
1018- !answer.location.as_deref().unwrap_or_default().contains("refusal="),1277+ !answer
1278+ .location
1279+ .as_deref()
1280+ .unwrap_or_default()
1281+ .contains("refusal="),
1019 "a move that worked said it was refused: {:?}",1282 "a move that worked said it was refused: {:?}",
1020 answer.location1283 answer.location
1021 );1284 );
1022 1285
1023- let answer = app.post("/api/fetch_task", Some(&admin), &[("task_id", &task)]).await;1286+ let answer = app
1287+ .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1288+ .await;
1024 assert!(answer.body.contains("\"moved\""), "no move in the activity");1289 assert!(answer.body.contains("\"moved\""), "no move in the activity");
1025 }1290 }
1026 1291
@@ -1038,7 +1303,11 @@ async fn a_successful_move_never_redirects_off_site() {
1038 "/api/move_card",1303 "/api/move_card",
1039 Some(&admin),1304 Some(&admin),
1040 "https://elsewhere.example/steal",1305 "https://elsewhere.example/steal",
1041- &[("task_id", &task), ("from_column_id", &columns[0]), ("to_column_id", &columns[1])],1306+ &[
1307+ ("task_id", &task),
1308+ ("from_column_id", &columns[0]),
1309+ ("to_column_id", &columns[1]),
1310+ ],
1042 )1311 )
1043 .await;1312 .await;
1044 assert_eq!(answer.status, StatusCode::SEE_OTHER);1313 assert_eq!(answer.status, StatusCode::SEE_OTHER);
@@ -1062,7 +1331,11 @@ async fn a_drop_decided_against_a_stale_board_is_refused() {
1062 .post(1331 .post(
1063 "/api/move_card",1332 "/api/move_card",
1064 Some(&admin),1333 Some(&admin),
1065- &[("task_id", &task), ("from_column_id", &columns[0]), ("to_column_id", &columns[1])],1334+ &[
1335+ ("task_id", &task),
1336+ ("from_column_id", &columns[0]),
1337+ ("to_column_id", &columns[1]),
1338+ ],
1066 )1339 )
1067 .await;1340 .await;
1068 assert_eq!(first.body, "");1341 assert_eq!(first.body, "");
@@ -1071,18 +1344,28 @@ async fn a_drop_decided_against_a_stale_board_is_refused() {
1071 .post(1344 .post(
1072 "/api/move_card",1345 "/api/move_card",
1073 Some(&member),1346 Some(&member),
1074- &[("task_id", &task), ("from_column_id", &columns[0]), ("to_column_id", &columns[2])],1347+ &[
1348+ ("task_id", &task),
1349+ ("from_column_id", &columns[0]),
1350+ ("to_column_id", &columns[2]),
1351+ ],
1075 )1352 )
1076 .await;1353 .await;
1077 assert_eq!(second.body, "");1354 assert_eq!(second.body, "");
1078 assert!(1355 assert!(
1079- second.location.as_deref().unwrap_or_default().contains("refusal=moved-already&on=move_card"),1356+ second
1357+ .location
1358+ .as_deref()
1359+ .unwrap_or_default()
1360+ .contains("refusal=moved-already&on=move_card"),
1080 "{:?}",1361 "{:?}",
1081 second.location1362 second.location
1082 );1363 );
1083 1364
1084 // The winner's move stands, and there is exactly one crossing.1365 // The winner's move stands, and there is exactly one crossing.
1085- let answer = app.post("/api/fetch_task", Some(&admin), &[("task_id", &task)]).await;1366+ let answer = app
1367+ .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1368+ .await;
1086 assert_eq!(1369 assert_eq!(
1087 answer.body.matches("\"moved\"").count(),1370 answer.body.matches("\"moved\"").count(),
1088 1,1371 1,
@@ -1111,12 +1394,21 @@ async fn a_card_cannot_be_moved_into_another_boards_column() {
1111 .await;1394 .await;
1112 assert_eq!(answer.body, "");1395 assert_eq!(answer.body, "");
1113 assert!(1396 assert!(
1114- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=move_card"),1397+ answer
1398+ .location
1399+ .as_deref()
1400+ .unwrap_or_default()
1401+ .contains("refusal=forbidden&on=move_card"),
1115 "{:?}",1402 "{:?}",
1116 answer.location1403 answer.location
1117 );1404 );
1118- let answer = app.post("/api/fetch_task", Some(&admin), &[("task_id", &task)]).await;1405+ let answer = app
1119- assert!(answer.body.contains(&columns[0]), "the forbidden move happened anyway");1406+ .post("/api/fetch_task", Some(&admin), &[("task_id", &task)])
1407+ .await;
1408+ assert!(
1409+ answer.body.contains(&columns[0]),
1410+ "the forbidden move happened anyway"
1411+ );
1120 }1412 }
1121 1413
1122 // ---------------------------------------------------------------------------1414 // ---------------------------------------------------------------------------
@@ -1135,10 +1427,22 @@ async fn settings_selects_keep_their_hidden_form_fields_and_get_a_dropdown_trigg
1135 1427
1136 let page = app.get("/settings", Some(&cookie)).await;1428 let page = app.get("/settings", Some(&cookie)).await;
1137 let html = String::from_utf8_lossy(&page.bytes);1429 let html = String::from_utf8_lossy(&page.bytes);
1138- assert!(html.contains("select class=\"field-input\" name=\"theme\""), "{html}");1430+ assert!(
1139- assert!(html.contains("dd-trigger"), "no dropdown script on the settings page: {html}");1431+ html.contains("select class=\"field-input\" name=\"theme\""),
1140- assert!(html.contains("__izlekEsc.register(40"), "no escape script on the settings page: {html}");1432+ "{html}"
1141- assert!(html.contains("closest('.user-menu')"), "no user-menu close path on the settings page: {html}");1433+ );
1434+ assert!(
1435+ html.contains("dd-trigger"),
1436+ "no dropdown script on the settings page: {html}"
1437+ );
1438+ assert!(
1439+ html.contains("__izlekEsc.register(40"),
1440+ "no escape script on the settings page: {html}"
1441+ );
1442+ assert!(
1443+ html.contains("closest('.user-menu')"),
1444+ "no user-menu close path on the settings page: {html}"
1445+ );
1142 }1446 }
1143 1447
1144 /// The rules and logs pages carry no `board.rs`, so like settings they wire1448 /// The rules and logs pages carry no `board.rs`, so like settings they wire
@@ -1151,12 +1455,21 @@ async fn the_rules_and_logs_pages_get_the_shared_escape_script() {
1151 1455
1152 let rules_page = app.get("/rules", Some(&cookie)).await;1456 let rules_page = app.get("/rules", Some(&cookie)).await;
1153 let rules_html = String::from_utf8_lossy(&rules_page.bytes);1457 let rules_html = String::from_utf8_lossy(&rules_page.bytes);
1154- assert!(rules_html.contains("__izlekEsc.register(40"), "no escape script on the rules page: {rules_html}");1458+ assert!(
1155- assert!(rules_html.contains("details.rule-new[open]"), "escape script does not close the rule composer: {rules_html}");1459+ rules_html.contains("__izlekEsc.register(40"),
1460+ "no escape script on the rules page: {rules_html}"
1461+ );
1462+ assert!(
1463+ rules_html.contains("details.rule-new[open]"),
1464+ "escape script does not close the rule composer: {rules_html}"
1465+ );
1156 1466
1157 let logs_page = app.get("/logs", Some(&cookie)).await;1467 let logs_page = app.get("/logs", Some(&cookie)).await;
1158 let logs_html = String::from_utf8_lossy(&logs_page.bytes);1468 let logs_html = String::from_utf8_lossy(&logs_page.bytes);
1159- assert!(logs_html.contains("__izlekEsc.register(40"), "no escape script on the logs page: {logs_html}");1469+ assert!(
1470+ logs_html.contains("__izlekEsc.register(40"),
1471+ "no escape script on the logs page: {logs_html}"
1472+ );
1160 }1473 }
1161 1474
1162 #[tokio::test]1475 #[tokio::test]
@@ -1186,7 +1499,12 @@ async fn signing_out_without_script_lands_on_the_sign_in_page() {
1186 let cookie = admin(&app).await;1499 let cookie = admin(&app).await;
1187 1500
1188 let out = app1501 let out = app
1189- .post_without_script("/api/sign_out", Some(&cookie), "http://izlek.test/settings", &[])1502+ .post_without_script(
1503+ "/api/sign_out",
1504+ Some(&cookie),
1505+ "http://izlek.test/settings",
1506+ &[],
1507+ )
1190 .await;1508 .await;
1191 1509
1192 assert_eq!(out.status, StatusCode::SEE_OTHER, "{}", out.body);1510 assert_eq!(out.status, StatusCode::SEE_OTHER, "{}", out.body);
@@ -1213,10 +1531,20 @@ async fn saving_a_profile_renames_the_person_asking_and_nobody_else() {
1213 let admin_cookie = admin(&app).await;1531 let admin_cookie = admin(&app).await;
1214 let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;1532 let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
1215 1533
1216- let answer = app.post("/api/save_profile", Some(&member), &[("display_name", "Emre Y")]).await;1534+ let answer = app
1535+ .post(
1536+ "/api/save_profile",
1537+ Some(&member),
1538+ &[("display_name", "Emre Y")],
1539+ )
1540+ .await;
1217 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);1541 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
1218 assert!(1542 assert!(
1219- !answer.location.as_deref().unwrap_or_default().contains("refusal="),1543+ !answer
1544+ .location
1545+ .as_deref()
1546+ .unwrap_or_default()
1547+ .contains("refusal="),
1220 "{:?}",1548 "{:?}",
1221 answer.location1549 answer.location
1222 );1550 );
@@ -1235,10 +1563,19 @@ async fn a_profile_cannot_be_saved_without_a_name() {
1235 let app = App::open().await;1563 let app = App::open().await;
1236 let admin_cookie = admin(&app).await;1564 let admin_cookie = admin(&app).await;
1237 1565
1238- let answer = app.post("/api/save_profile", Some(&admin_cookie), &[("display_name", " ")]).await;1566+ let answer = app
1567+ .post(
1568+ "/api/save_profile",
1569+ Some(&admin_cookie),
1570+ &[("display_name", " ")],
1571+ )
1572+ .await;
1239 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);1573 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
1240 let location = answer.location.as_deref().unwrap_or_default();1574 let location = answer.location.as_deref().unwrap_or_default();
1241- assert!(location.contains("refusal=empty-name&on=save_profile"), "{location}");1575+ assert!(
1576+ location.contains("refusal=empty-name&on=save_profile"),
1577+ "{location}"
1578+ );
1242 1579
1243 let page = app.get(location, Some(&admin_cookie)).await;1580 let page = app.get(location, Some(&admin_cookie)).await;
1244 let html = String::from_utf8_lossy(&page.bytes);1581 let html = String::from_utf8_lossy(&page.bytes);
@@ -1260,7 +1597,11 @@ async fn a_profile_can_change_its_own_email_and_stays_signed_in() {
1260 .await;1597 .await;
1261 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);1598 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
1262 assert!(1599 assert!(
1263- !answer.location.as_deref().unwrap_or_default().contains("refusal="),1600+ !answer
1601+ .location
1602+ .as_deref()
1603+ .unwrap_or_default()
1604+ .contains("refusal="),
1264 "{:?}",1605 "{:?}",
1265 answer.location1606 answer.location
1266 );1607 );
@@ -1286,7 +1627,10 @@ async fn a_profile_email_cannot_take_somebody_elses_address() {
1286 )1627 )
1287 .await;1628 .await;
1288 let location = answer.location.as_deref().unwrap_or_default();1629 let location = answer.location.as_deref().unwrap_or_default();
1289- assert!(location.contains("refusal=address-taken&on=save_profile"), "{location}");1630+ assert!(
1631+ location.contains("refusal=address-taken&on=save_profile"),
1632+ "{location}"
1633+ );
1290 1634
1291 let page = app.get(location, Some(&member)).await;1635 let page = app.get(location, Some(&member)).await;
1292 let html = String::from_utf8_lossy(&page.bytes);1636 let html = String::from_utf8_lossy(&page.bytes);
@@ -1313,11 +1657,17 @@ async fn a_taken_email_refuses_the_whole_save_not_only_the_email() {
1313 )1657 )
1314 .await;1658 .await;
1315 let location = answer.location.as_deref().unwrap_or_default();1659 let location = answer.location.as_deref().unwrap_or_default();
1316- assert!(location.contains("refusal=address-taken&on=save_profile"), "{location}");1660+ assert!(
1661+ location.contains("refusal=address-taken&on=save_profile"),
1662+ "{location}"
1663+ );
1317 1664
1318 let mine = app.get("/settings", Some(&member)).await;1665 let mine = app.get("/settings", Some(&member)).await;
1319 let html = String::from_utf8_lossy(&mine.bytes);1666 let html = String::from_utf8_lossy(&mine.bytes);
1320- assert!(html.contains("value=\"Emre\""), "the name changed anyway: {html}");1667+ assert!(
1668+ html.contains("value=\"Emre\""),
1669+ "the name changed anyway: {html}"
1670+ );
1321 }1671 }
1322 1672
1323 #[tokio::test]1673 #[tokio::test]
@@ -1325,10 +1675,16 @@ async fn a_signed_out_browser_cannot_rename_anybody() {
1325 let app = App::open().await;1675 let app = App::open().await;
1326 let _ = admin(&app).await;1676 let _ = admin(&app).await;
1327 1677
1328- let answer = app.post("/api/save_profile", None, &[("display_name", "Whoever")]).await;1678+ let answer = app
1679+ .post("/api/save_profile", None, &[("display_name", "Whoever")])
1680+ .await;
1329 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);1681 assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
1330 assert!(1682 assert!(
1331- answer.location.as_deref().unwrap_or_default().contains("refusal=sign-in-first&on=save_profile"),1683+ answer
1684+ .location
1685+ .as_deref()
1686+ .unwrap_or_default()
1687+ .contains("refusal=sign-in-first&on=save_profile"),
1332 "{:?}",1688 "{:?}",
1333 answer.location1689 answer.location
1334 );1690 );
@@ -1344,11 +1700,19 @@ async fn a_member_who_posts_new_limits_anyway_is_refused() {
1344 .post(1700 .post(
1345 "/api/save_limits",1701 "/api/save_limits",
1346 Some(&member),1702 Some(&member),
1347- &[("attachment_limit_mb", "400"), ("photo_limit_mb", "19"), ("allowed_file_types", "png")],1703+ &[
1704+ ("attachment_limit_mb", "400"),
1705+ ("photo_limit_mb", "19"),
1706+ ("allowed_file_types", "png"),
1707+ ],
1348 )1708 )
1349 .await;1709 .await;
1350 assert!(1710 assert!(
1351- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=save_limits"),1711+ answer
1712+ .location
1713+ .as_deref()
1714+ .unwrap_or_default()
1715+ .contains("refusal=forbidden&on=save_limits"),
1352 "{:?}",1716 "{:?}",
1353 answer.location1717 answer.location
1354 );1718 );
@@ -1367,11 +1731,19 @@ async fn an_admin_changes_the_limits_and_they_stay_changed() {
1367 .post(1731 .post(
1368 "/api/save_limits",1732 "/api/save_limits",
1369 Some(&admin_cookie),1733 Some(&admin_cookie),
1370- &[("attachment_limit_mb", "10"), ("photo_limit_mb", "1"), ("allowed_file_types", ".PNG, png, pdf")],1734+ &[
1735+ ("attachment_limit_mb", "10"),
1736+ ("photo_limit_mb", "1"),
1737+ ("allowed_file_types", ".PNG, png, pdf"),
1738+ ],
1371 )1739 )
1372 .await;1740 .await;
1373 assert!(1741 assert!(
1374- answer.location.as_deref().unwrap_or_default().contains("saved=save_limits"),1742+ answer
1743+ .location
1744+ .as_deref()
1745+ .unwrap_or_default()
1746+ .contains("saved=save_limits"),
1375 "{:?}",1747 "{:?}",
1376 answer.location1748 answer.location
1377 );1749 );
@@ -1379,7 +1751,10 @@ async fn an_admin_changes_the_limits_and_they_stay_changed() {
1379 let workspace = app.store.workspace().await.unwrap().unwrap();1751 let workspace = app.store.workspace().await.unwrap().unwrap();
1380 assert_eq!(workspace.attachment_limit_bytes, 10 * 1024 * 1024);1752 assert_eq!(workspace.attachment_limit_bytes, 10 * 1024 * 1024);
1381 assert_eq!(workspace.photo_limit_bytes, 1024 * 1024);1753 assert_eq!(workspace.photo_limit_bytes, 1024 * 1024);
1382- assert_eq!(workspace.allowed_file_types, vec!["png".to_string(), "pdf".to_string()]);1754+ assert_eq!(
1755+ workspace.allowed_file_types,
1756+ vec!["png".to_string(), "pdf".to_string()]
1757+ );
1383 }1758 }
1384 1759
1385 #[tokio::test]1760 #[tokio::test]
@@ -1392,11 +1767,18 @@ async fn a_limit_outside_what_the_disk_should_promise_is_refused() {
1392 .post(1767 .post(
1393 "/api/save_limits",1768 "/api/save_limits",
1394 Some(&admin_cookie),1769 Some(&admin_cookie),
1395- &[("attachment_limit_mb", attachment), ("photo_limit_mb", photo), ("allowed_file_types", "")],1770+ &[
1771+ ("attachment_limit_mb", attachment),
1772+ ("photo_limit_mb", photo),
1773+ ("allowed_file_types", ""),
1774+ ],
1396 )1775 )
1397 .await;1776 .await;
1398 let location = answer.location.as_deref().unwrap_or_default();1777 let location = answer.location.as_deref().unwrap_or_default();
1399- assert!(location.contains("refusal=bad-limit&on=save_limits"), "{attachment}/{photo}: {location}");1778+ assert!(
1779+ location.contains("refusal=bad-limit&on=save_limits"),
1780+ "{attachment}/{photo}: {location}"
1781+ );
1400 1782
1401 let page = app.get(location, Some(&admin_cookie)).await;1783 let page = app.get(location, Some(&admin_cookie)).await;
1402 let html = String::from_utf8_lossy(&page.bytes);1784 let html = String::from_utf8_lossy(&page.bytes);
@@ -1416,11 +1798,18 @@ async fn a_file_type_that_is_not_an_extension_is_refused() {
1416 .post(1798 .post(
1417 "/api/save_limits",1799 "/api/save_limits",
1418 Some(&admin_cookie),1800 Some(&admin_cookie),
1419- &[("attachment_limit_mb", "25"), ("photo_limit_mb", "2"), ("allowed_file_types", "../etc/passwd")],1801+ &[
1802+ ("attachment_limit_mb", "25"),
1803+ ("photo_limit_mb", "2"),
1804+ ("allowed_file_types", "../etc/passwd"),
1805+ ],
1420 )1806 )
1421 .await;1807 .await;
1422 let location = answer.location.as_deref().unwrap_or_default();1808 let location = answer.location.as_deref().unwrap_or_default();
1423- assert!(location.contains("refusal=bad-file-type&on=save_limits"), "{location}");1809+ assert!(
1810+ location.contains("refusal=bad-file-type&on=save_limits"),
1811+ "{location}"
1812+ );
1424 1813
1425 let page = app.get(location, Some(&admin_cookie)).await;1814 let page = app.get(location, Some(&admin_cookie)).await;
1426 let html = String::from_utf8_lossy(&page.bytes);1815 let html = String::from_utf8_lossy(&page.bytes);
@@ -1448,7 +1837,11 @@ async fn only_an_admin_may_write_the_sender() {
1448 )1837 )
1449 .await;1838 .await;
1450 assert!(1839 assert!(
1451- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=save_sender"),1840+ answer
1841+ .location
1842+ .as_deref()
1843+ .unwrap_or_default()
1844+ .contains("refusal=forbidden&on=save_sender"),
1452 "{:?}",1845 "{:?}",
1453 answer.location1846 answer.location
1454 );1847 );
@@ -1481,7 +1874,11 @@ async fn a_signed_out_browser_may_not_write_the_sender() {
1481 )1874 )
1482 .await;1875 .await;
1483 assert!(1876 assert!(
1484- answer.location.as_deref().unwrap_or_default().contains("refusal=sign-in-first&on=save_sender"),1877+ answer
1878+ .location
1879+ .as_deref()
1880+ .unwrap_or_default()
1881+ .contains("refusal=sign-in-first&on=save_sender"),
1485 "{:?}",1882 "{:?}",
1486 answer.location1883 answer.location
1487 );1884 );
@@ -1511,14 +1908,21 @@ async fn an_edit_with_no_password_typed_keeps_the_stored_one() {
1511 )1908 )
1512 .await;1909 .await;
1513 assert!(1910 assert!(
1514- !answer.location.as_deref().unwrap_or_default().contains("refusal="),1911+ !answer
1912+ .location
1913+ .as_deref()
1914+ .unwrap_or_default()
1915+ .contains("refusal="),
1515 "an empty password field was refused: {:?}",1916 "an empty password field was refused: {:?}",
1516 answer.location1917 answer.location
1517 );1918 );
1518 1919
1519 let workspace = app.store.workspace().await.unwrap().unwrap();1920 let workspace = app.store.workspace().await.unwrap().unwrap();
1520 assert_eq!(workspace.smtp_port, Some(587));1921 assert_eq!(workspace.smtp_port, Some(587));
1521- assert!(workspace.smtp_password_set, "an empty field blanked the password");1922+ assert!(
1923+ workspace.smtp_password_set,
1924+ "an empty field blanked the password"
1925+ );
1522 }1926 }
1523 1927
1524 #[tokio::test]1928 #[tokio::test]
@@ -1541,11 +1945,17 @@ async fn a_first_sender_with_no_password_is_refused_and_says_why() {
1541 )1945 )
1542 .await;1946 .await;
1543 let location = answer.location.as_deref().unwrap_or_default();1947 let location = answer.location.as_deref().unwrap_or_default();
1544- assert!(location.contains("refusal=bad-sender&on=save_sender"), "{location}");1948+ assert!(
1949+ location.contains("refusal=bad-sender&on=save_sender"),
1950+ "{location}"
1951+ );
1545 1952
1546 let page = app.get(location, Some(&admin_cookie)).await;1953 let page = app.get(location, Some(&admin_cookie)).await;
1547 let html = String::from_utf8_lossy(&page.bytes);1954 let html = String::from_utf8_lossy(&page.bytes);
1548- assert!(html.contains("A password is needed the first time."), "{html}");1955+ assert!(
1956+ html.contains("A password is needed the first time."),
1957+ "{html}"
1958+ );
1549 }1959 }
1550 1960
1551 #[tokio::test]1961 #[tokio::test]
@@ -1560,11 +1970,27 @@ async fn a_sender_field_that_cannot_work_is_refused_by_name() {
1560 &[("host", "smtp.fastmail.com/inbox")],1970 &[("host", "smtp.fastmail.com/inbox")],
1561 "The SMTP host is a host name, not an address or a URL.",1971 "The SMTP host is a host name, not an address or a URL.",
1562 ),1972 ),
1563- ("port", &[("port", "0")], "A port is a number between 1 and 65535."),1973+ (
1564- ("port", &[("port", "99999")], "A port is a number between 1 and 65535."),1974+ "port",
1975+ &[("port", "0")],
1976+ "A port is a number between 1 and 65535.",
1977+ ),
1978+ (
1979+ "port",
1980+ &[("port", "99999")],
1981+ "A port is a number between 1 and 65535.",
1982+ ),
1565 ("username", &[("username", "")], "Give the SMTP username."),1983 ("username", &[("username", "")], "Give the SMTP username."),
1566- ("from_address", &[("from_address", "board-at-izlek")], "That is not a from-address."),1984+ (
1567- ("from_address", &[("from_address", "board@izlek")], "That is not a from-address."),1985+ "from_address",
1986+ &[("from_address", "board-at-izlek")],
1987+ "That is not a from-address.",
1988+ ),
1989+ (
1990+ "from_address",
1991+ &[("from_address", "board@izlek")],
1992+ "That is not a from-address.",
1993+ ),
1568 ];1994 ];
1569 for (field, overrides, expected) in bad {1995 for (field, overrides, expected) in bad {
1570 let mut form: Vec<(&str, &str)> = vec![1996 let mut form: Vec<(&str, &str)> = vec![
@@ -1582,7 +2008,9 @@ async fn a_sender_field_that_cannot_work_is_refused_by_name() {
1582 }2008 }
1583 }2009 }
1584 }2010 }
1585- let answer = app.post("/api/save_sender", Some(&admin_cookie), &form).await;2011+ let answer = app
2012+ .post("/api/save_sender", Some(&admin_cookie), &form)
2013+ .await;
1586 let location = answer.location.as_deref().unwrap_or_default();2014 let location = answer.location.as_deref().unwrap_or_default();
1587 assert!(2015 assert!(
1588 location.contains("refusal=bad-sender&on=save_sender"),2016 location.contains("refusal=bad-sender&on=save_sender"),
@@ -1603,7 +2031,11 @@ async fn a_member_may_not_press_the_test_button() {
1603 2031
1604 let answer = app.post("/api/send_test_mail", Some(&member), &[]).await;2032 let answer = app.post("/api/send_test_mail", Some(&member), &[]).await;
1605 assert!(2033 assert!(
1606- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=send_test_mail"),2034+ answer
2035+ .location
2036+ .as_deref()
2037+ .unwrap_or_default()
2038+ .contains("refusal=forbidden&on=send_test_mail"),
1607 "{:?}",2039 "{:?}",
1608 answer.location2040 answer.location
1609 );2041 );
@@ -1617,7 +2049,11 @@ async fn a_viewer_may_not_press_the_test_button() {
1617 2049
1618 let answer = app.post("/api/send_test_mail", Some(&viewer), &[]).await;2050 let answer = app.post("/api/send_test_mail", Some(&viewer), &[]).await;
1619 assert!(2051 assert!(
1620- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=send_test_mail"),2052+ answer
2053+ .location
2054+ .as_deref()
2055+ .unwrap_or_default()
2056+ .contains("refusal=forbidden&on=send_test_mail"),
1621 "{:?}",2057 "{:?}",
1622 answer.location2058 answer.location
1623 );2059 );
@@ -1629,7 +2065,11 @@ async fn a_signed_out_browser_may_not_press_the_test_button() {
1629 2065
1630 let answer = app.post("/api/send_test_mail", None, &[]).await;2066 let answer = app.post("/api/send_test_mail", None, &[]).await;
1631 assert!(2067 assert!(
1632- answer.location.as_deref().unwrap_or_default().contains("refusal=sign-in-first&on=send_test_mail"),2068+ answer
2069+ .location
2070+ .as_deref()
2071+ .unwrap_or_default()
2072+ .contains("refusal=sign-in-first&on=send_test_mail"),
1633 "{:?}",2073 "{:?}",
1634 answer.location2074 answer.location
1635 );2075 );
@@ -1640,16 +2080,25 @@ async fn testing_a_sender_that_was_never_filled_in_says_so_rather_than_sending()
1640 let app = App::open().await;2080 let app = App::open().await;
1641 let admin_cookie = admin(&app).await;2081 let admin_cookie = admin(&app).await;
1642 2082
1643- let answer = app.post("/api/send_test_mail", Some(&admin_cookie), &[]).await;2083+ let answer = app
2084+ .post("/api/send_test_mail", Some(&admin_cookie), &[])
2085+ .await;
1644 assert!(2086 assert!(
1645- answer.location.as_deref().unwrap_or_default().contains("refusal=bad-sender&on=send_test_mail"),2087+ answer
2088+ .location
2089+ .as_deref()
2090+ .unwrap_or_default()
2091+ .contains("refusal=bad-sender&on=send_test_mail"),
1646 "{:?}",2092 "{:?}",
1647 answer.location2093 answer.location
1648 );2094 );
1649 2095
1650 // Nothing was recorded either: the panel still has no test line to show.2096 // Nothing was recorded either: the panel still has no test line to show.
1651 let workspace = app.store.workspace().await.unwrap().unwrap();2097 let workspace = app.store.workspace().await.unwrap().unwrap();
1652- assert!(workspace.sender_test.is_none(), "a test with no sender recorded a result");2098+ assert!(
2099+ workspace.sender_test.is_none(),
2100+ "a test with no sender recorded a result"
2101+ );
1653 }2102 }
1654 2103
1655 #[tokio::test]2104 #[tokio::test]
@@ -1658,7 +2107,15 @@ async fn a_member_who_posts_a_resend_anyway_is_refused() {
1658 let admin_cookie = admin(&app).await;2107 let admin_cookie = admin(&app).await;
1659 let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;2108 let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
1660 let mert = app2109 let mert = app
1661- .post("/api/invite_member", Some(&admin_cookie), &[("email", "mert@izlek.sh"), ("display_name", "Mert"), ("role", "member")])2110+ .post(
2111+ "/api/invite_member",
2112+ Some(&admin_cookie),
2113+ &[
2114+ ("email", "mert@izlek.sh"),
2115+ ("display_name", "Mert"),
2116+ ("role", "member"),
2117+ ],
2118+ )
1662 .await;2119 .await;
1663 assert_eq!(mert.status, StatusCode::OK, "{}", mert.body);2120 assert_eq!(mert.status, StatusCode::OK, "{}", mert.body);
1664 let workspace_id = app.workspace_id().await;2121 let workspace_id = app.workspace_id().await;
@@ -1672,13 +2129,27 @@ async fn a_member_who_posts_a_resend_anyway_is_refused() {
1672 .expect("no member row for mert")2129 .expect("no member row for mert")
1673 .id;2130 .id;
1674 2131
1675- let answer = app.post("/api/resend_link", Some(&member), &[("user_id", &mert_id)]).await;2132+ let answer = app
2133+ .post("/api/resend_link", Some(&member), &[("user_id", &mert_id)])
2134+ .await;
2135+ assert!(
2136+ answer
2137+ .location
2138+ .as_deref()
2139+ .unwrap_or_default()
2140+ .contains("refusal=forbidden&on=resend_link"),
2141+ "{:?}",
2142+ answer.location
2143+ );
1676 assert!(2144 assert!(
1677- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=resend_link"),2145+ !answer
2146+ .location
2147+ .as_deref()
2148+ .unwrap_or_default()
2149+ .contains("mailed="),
1678 "{:?}",2150 "{:?}",
1679 answer.location2151 answer.location
1680 );2152 );
1681- assert!(!answer.location.as_deref().unwrap_or_default().contains("mailed="), "{:?}", answer.location);
1682 }2153 }
1683 2154
1684 #[tokio::test]2155 #[tokio::test]
@@ -1686,9 +2157,17 @@ async fn a_resent_link_opens_the_same_account() {
1686 let app = App::open().await;2157 let app = App::open().await;
1687 let admin_cookie = admin(&app).await;2158 let admin_cookie = admin(&app).await;
1688 let invitation = app2159 let invitation = app
1689- .post("/api/invite_member", Some(&admin_cookie), &[("email", "mert@izlek.sh"), ("display_name", "Mert"), ("role", "member")])2160+ .post(
1690- .await;2161+ "/api/invite_member",
1691- assert_eq!(invitation.status, StatusCode::OK, "{}", invitation.body);2162+ Some(&admin_cookie),
2163+ &[
2164+ ("email", "mert@izlek.sh"),
2165+ ("display_name", "Mert"),
2166+ ("role", "member"),
2167+ ],
2168+ )
2169+ .await;
2170+ assert_eq!(invitation.status, StatusCode::OK, "{}", invitation.body);
1692 let workspace_id = app.workspace_id().await;2171 let workspace_id = app.workspace_id().await;
1693 let mert_id = app2172 let mert_id = app
1694 .store2173 .store
@@ -1700,18 +2179,40 @@ async fn a_resent_link_opens_the_same_account() {
1700 .expect("no member row for mert")2179 .expect("no member row for mert")
1701 .id;2180 .id;
1702 2181
1703- let answer = app.post("/api/resend_link", Some(&admin_cookie), &[("user_id", &mert_id)]).await;2182+ let answer = app
2183+ .post(
2184+ "/api/resend_link",
2185+ Some(&admin_cookie),
2186+ &[("user_id", &mert_id)],
2187+ )
2188+ .await;
1704 assert!(2189 assert!(
1705- answer.location.as_deref().unwrap_or_default().contains("mailed=mert%40izlek.sh"),2190+ answer
2191+ .location
2192+ .as_deref()
2193+ .unwrap_or_default()
2194+ .contains("mailed=mert%40izlek.sh"),
1706 "{:?}",2195 "{:?}",
1707 answer.location2196 answer.location
1708 );2197 );
1709 let token = queued_join_token(&app, "mert@izlek.sh").await;2198 let token = queued_join_token(&app, "mert@izlek.sh").await;
1710 2199
1711- let redeemed = app.post("/api/redeem_link", None, &[("token", &token), ("password", "lantern gravel spoon meadow")]).await;2200+ let redeemed = app
2201+ .post(
2202+ "/api/redeem_link",
2203+ None,
2204+ &[
2205+ ("token", &token),
2206+ ("password", "lantern gravel spoon meadow"),
2207+ ],
2208+ )
2209+ .await;
1712 assert_eq!(redeemed.status, StatusCode::SEE_OTHER, "{}", redeemed.body);2210 assert_eq!(redeemed.status, StatusCode::SEE_OTHER, "{}", redeemed.body);
1713 assert_eq!(redeemed.body, "null", "{}", redeemed.body);2211 assert_eq!(redeemed.body, "null", "{}", redeemed.body);
1714- assert!(redeemed.session.is_some(), "the resent link signed nobody in");2212+ assert!(
2213+ redeemed.session.is_some(),
2214+ "the resent link signed nobody in"
2215+ );
1715 }2216 }
1716 2217
1717 #[tokio::test]2218 #[tokio::test]
@@ -1719,7 +2220,15 @@ async fn an_admin_may_change_a_members_role_over_http() {
1719 let app = App::open().await;2220 let app = App::open().await;
1720 let admin_cookie = admin(&app).await;2221 let admin_cookie = admin(&app).await;
1721 let mert = app2222 let mert = app
1722- .post("/api/invite_member", Some(&admin_cookie), &[("email", "mert@izlek.sh"), ("display_name", "Mert"), ("role", "member")])2223+ .post(
2224+ "/api/invite_member",
2225+ Some(&admin_cookie),
2226+ &[
2227+ ("email", "mert@izlek.sh"),
2228+ ("display_name", "Mert"),
2229+ ("role", "member"),
2230+ ],
2231+ )
1723 .await;2232 .await;
1724 assert_eq!(mert.status, StatusCode::OK, "{}", mert.body);2233 assert_eq!(mert.status, StatusCode::OK, "{}", mert.body);
1725 let workspace_id = app.workspace_id().await;2234 let workspace_id = app.workspace_id().await;
@@ -1733,9 +2242,19 @@ async fn an_admin_may_change_a_members_role_over_http() {
1733 .expect("no member row for mert")2242 .expect("no member row for mert")
1734 .id;2243 .id;
1735 2244
1736- let answer = app.post("/api/set_role", Some(&admin_cookie), &[("user_id", &mert_id), ("role", "viewer")]).await;2245+ let answer = app
2246+ .post(
2247+ "/api/set_role",
2248+ Some(&admin_cookie),
2249+ &[("user_id", &mert_id), ("role", "viewer")],
2250+ )
2251+ .await;
1737 assert!(2252 assert!(
1738- answer.location.as_deref().unwrap_or_default().contains("saved=set_role"),2253+ answer
2254+ .location
2255+ .as_deref()
2256+ .unwrap_or_default()
2257+ .contains("saved=set_role"),
1739 "{:?}",2258 "{:?}",
1740 answer.location2259 answer.location
1741 );2260 );
@@ -1756,15 +2275,29 @@ async fn the_owner_cannot_be_retargeted_over_http() {
1756 .expect("workspace has no owner")2275 .expect("workspace has no owner")
1757 .id;2276 .id;
1758 2277
1759- let answer = app.post("/api/set_role", Some(&admin_cookie), &[("user_id", &owner_id), ("role", "member")]).await;2278+ let answer = app
2279+ .post(
2280+ "/api/set_role",
2281+ Some(&admin_cookie),
2282+ &[("user_id", &owner_id), ("role", "member")],
2283+ )
2284+ .await;
1760 assert!(2285 assert!(
1761- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=set_role"),2286+ answer
2287+ .location
2288+ .as_deref()
2289+ .unwrap_or_default()
2290+ .contains("refusal=forbidden&on=set_role"),
1762 "{:?}",2291 "{:?}",
1763 answer.location2292 answer.location
1764 );2293 );
1765 2294
1766 let reloaded = app.store.user(&owner_id).await.unwrap().unwrap();2295 let reloaded = app.store.user(&owner_id).await.unwrap().unwrap();
1767- assert_eq!(reloaded.role, Role::Admin, "the owner's role changed anyway");2296+ assert_eq!(
2297+ reloaded.role,
2298+ Role::Admin,
2299+ "the owner's role changed anyway"
2300+ );
1768 }2301 }
1769 2302
1770 #[tokio::test]2303 #[tokio::test]
@@ -1773,7 +2306,15 @@ async fn a_non_admin_may_not_set_roles_over_http() {
1773 let admin_cookie = admin(&app).await;2306 let admin_cookie = admin(&app).await;
1774 let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;2307 let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
1775 let mert = app2308 let mert = app
1776- .post("/api/invite_member", Some(&admin_cookie), &[("email", "mert@izlek.sh"), ("display_name", "Mert"), ("role", "member")])2309+ .post(
2310+ "/api/invite_member",
2311+ Some(&admin_cookie),
2312+ &[
2313+ ("email", "mert@izlek.sh"),
2314+ ("display_name", "Mert"),
2315+ ("role", "member"),
2316+ ],
2317+ )
1777 .await;2318 .await;
1778 assert_eq!(mert.status, StatusCode::OK, "{}", mert.body);2319 assert_eq!(mert.status, StatusCode::OK, "{}", mert.body);
1779 let workspace_id = app.workspace_id().await;2320 let workspace_id = app.workspace_id().await;
@@ -1787,23 +2328,45 @@ async fn a_non_admin_may_not_set_roles_over_http() {
1787 .expect("no member row for mert")2328 .expect("no member row for mert")
1788 .id;2329 .id;
1789 2330
1790- let answer = app.post("/api/set_role", Some(&member), &[("user_id", &mert_id), ("role", "admin")]).await;2331+ let answer = app
2332+ .post(
2333+ "/api/set_role",
2334+ Some(&member),
2335+ &[("user_id", &mert_id), ("role", "admin")],
2336+ )
2337+ .await;
1791 assert!(2338 assert!(
1792- answer.location.as_deref().unwrap_or_default().contains("refusal=forbidden&on=set_role"),2339+ answer
2340+ .location
2341+ .as_deref()
2342+ .unwrap_or_default()
2343+ .contains("refusal=forbidden&on=set_role"),
1793 "{:?}",2344 "{:?}",
1794 answer.location2345 answer.location
1795 );2346 );
1796 2347
1797 let reloaded = app.store.user(&mert_id).await.unwrap().unwrap();2348 let reloaded = app.store.user(&mert_id).await.unwrap().unwrap();
1798- assert_eq!(reloaded.role, Role::Member, "role change was not really refused");2349+ assert_eq!(
2350+ reloaded.role,
2351+ Role::Member,
2352+ "role change was not really refused"
2353+ );
1799 }2354 }
1800 2355
1801 #[tokio::test]2356 #[tokio::test]
1802 async fn redeeming_a_link_lands_on_the_board_not_the_spent_join_page() {2357 async fn redeeming_a_link_lands_on_the_board_not_the_spent_join_page() {
1803 let app = App::open().await;2358 let app = App::open().await;
1804 let admin_cookie = admin(&app).await;2359 let admin_cookie = admin(&app).await;
1805- app.post("/api/invite_member", Some(&admin_cookie), &[("email", "asli@izlek.sh"), ("display_name", "Asli"), ("role", "member")])2360+ app.post(
1806- .await;2361+ "/api/invite_member",
2362+ Some(&admin_cookie),
2363+ &[
2364+ ("email", "asli@izlek.sh"),
2365+ ("display_name", "Asli"),
2366+ ("role", "member"),
2367+ ],
2368+ )
2369+ .await;
1807 let token = queued_join_token(&app, "asli@izlek.sh").await;2370 let token = queued_join_token(&app, "asli@izlek.sh").await;
1808 2371
1809 let answer = app2372 let answer = app
@@ -1811,10 +2374,18 @@ async fn redeeming_a_link_lands_on_the_board_not_the_spent_join_page() {
1811 "/api/redeem_link",2374 "/api/redeem_link",
1812 None,2375 None,
1813 &format!("http://izlek.test/join/{token}"),2376 &format!("http://izlek.test/join/{token}"),
1814- &[("token", &token), ("password", "lantern gravel spoon meadow")],2377+ &[
2378+ ("token", &token),
2379+ ("password", "lantern gravel spoon meadow"),
2380+ ],
1815 )2381 )
1816 .await;2382 .await;
1817- assert_eq!(answer.location.as_deref(), Some("/"), "{:?}", answer.location);2383+ assert_eq!(
2384+ answer.location.as_deref(),
2385+ Some("/"),
2386+ "{:?}",
2387+ answer.location
2388+ );
1818 }2389 }
1819 2390
1820 #[tokio::test]2391 #[tokio::test]
@@ -1823,12 +2394,22 @@ async fn an_invitation_names_the_admin_who_made_it_and_not_the_invitee() {
1823 let admin_cookie = admin(&app).await;2394 let admin_cookie = admin(&app).await;
1824 2395
1825 let answer = app2396 let answer = app
1826- .post("/api/invite_member", Some(&admin_cookie), &[("email", "grace@izlek.sh"), ("display_name", "Grace Hopper"), ("role", "member")])2397+ .post(
2398+ "/api/invite_member",
2399+ Some(&admin_cookie),
2400+ &[
2401+ ("email", "grace@izlek.sh"),
2402+ ("display_name", "Grace Hopper"),
2403+ ("role", "member"),
2404+ ],
2405+ )
1827 .await;2406 .await;
1828 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);2407 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1829 let token = queued_join_token(&app, "grace@izlek.sh").await;2408 let token = queued_join_token(&app, "grace@izlek.sh").await;
1830 2409
1831- let answer = app.post("/api/invitation", None, &[("token", token.as_str())]).await;2410+ let answer = app
2411+ .post("/api/invitation", None, &[("token", token.as_str())])
2412+ .await;
1832 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);2413 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1833 assert!(2414 assert!(
1834 answer.body.contains(r#""invited_by":"Ada Lovelace""#),2415 answer.body.contains(r#""invited_by":"Ada Lovelace""#),
@@ -1911,14 +2492,25 @@ async fn an_admin_sees_who_has_a_password_and_never_a_hash() {
1911 let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;2492 let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
1912 // Invited and never signed in: the account exists, the password does not.2493 // Invited and never signed in: the account exists, the password does not.
1913 let answer = app2494 let answer = app
1914- .post("/api/invite_member", Some(&admin_cookie), &[("email", "mert@izlek.sh"), ("display_name", "Mert"), ("role", "member")])2495+ .post(
2496+ "/api/invite_member",
2497+ Some(&admin_cookie),
2498+ &[
2499+ ("email", "mert@izlek.sh"),
2500+ ("display_name", "Mert"),
2501+ ("role", "member"),
2502+ ],
2503+ )
1915 .await;2504 .await;
1916 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);2505 assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
1917 2506
1918 let page = app.get("/settings", Some(&admin_cookie)).await;2507 let page = app.get("/settings", Some(&admin_cookie)).await;
1919 let html = String::from_utf8_lossy(&page.bytes);2508 let html = String::from_utf8_lossy(&page.bytes);
1920 assert!(html.contains("mert@izlek.sh"), "{html}");2509 assert!(html.contains("mert@izlek.sh"), "{html}");
1921- assert!(html.contains("Resend mail"), "the un-signed-in member has no resend control: {html}");2510+ assert!(
2511+ html.contains("Resend mail"),
2512+ "the un-signed-in member has no resend control: {html}"
2513+ );
1922 assert!(!html.contains("$argon2"), "a hash reached the page: {html}");2514 assert!(!html.contains("$argon2"), "a hash reached the page: {html}");
1923 }2515 }
1924 2516
@@ -1932,7 +2524,12 @@ async fn rule_written(app: &App, admin: &str, column_id: &str, subject: &str) ->
1932 .post(2524 .post(
1933 "/api/create_rule",2525 "/api/create_rule",
1934 Some(admin),2526 Some(admin),
1935- &[("trigger", "status"), ("column_id", column_id), ("subject", subject), ("audience", "assignees")],2527+ &[
2528+ ("trigger", "status"),
2529+ ("column_id", column_id),
2530+ ("subject", subject),
2531+ ("audience", "assignees"),
2532+ ],
1936 )2533 )
1937 .await;2534 .await;
1938 answer.status == StatusCode::SEE_OTHER && answer.body == "null"2535 answer.status == StatusCode::SEE_OTHER && answer.body == "null"
@@ -1959,12 +2556,30 @@ async fn an_admin_writes_a_rule_and_reads_it_back_as_a_sentence() {
1959 2556
1960 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);2557 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
1961 2558
1962- let answer = app.post("/api/current_rules", Some(&admin_cookie), &[]).await;2559+ let answer = app
1963- assert!(answer.body.contains("\"when\":\"When status becomes\""), "{}", answer.body);2560+ .post("/api/current_rules", Some(&admin_cookie), &[])
1964- assert!(answer.body.contains("\"subject\":\"Task completed\""), "{}", answer.body);2561+ .await;
1965- assert!(answer.body.contains("\"audience\":\"assignees\""), "{}", answer.body);2562+ assert!(
2563+ answer.body.contains("\"when\":\"When status becomes\""),
2564+ "{}",
2565+ answer.body
2566+ );
2567+ assert!(
2568+ answer.body.contains("\"subject\":\"Task completed\""),
2569+ "{}",
2570+ answer.body
2571+ );
2572+ assert!(
2573+ answer.body.contains("\"audience\":\"assignees\""),
2574+ "{}",
2575+ answer.body
2576+ );
1966 // Nothing has been sent, and the row says so rather than nothing at all.2577 // Nothing has been sent, and the row says so rather than nothing at all.
1967- assert!(answer.body.contains("\"last_sent\":null"), "{}", answer.body);2578+ assert!(
2579+ answer.body.contains("\"last_sent\":null"),
2580+ "{}",
2581+ answer.body
2582+ );
1968 }2583 }
1969 2584
1970 #[tokio::test]2585 #[tokio::test]
@@ -1977,7 +2592,12 @@ async fn a_rule_with_no_subject_is_refused_and_says_why() {
1977 .post(2592 .post(
1978 "/api/create_rule",2593 "/api/create_rule",
1979 Some(&admin_cookie),2594 Some(&admin_cookie),
1980- &[("trigger", "status"), ("column_id", &column), ("subject", " "), ("audience", "assignees")],2595+ &[
2596+ ("trigger", "status"),
2597+ ("column_id", &column),
2598+ ("subject", " "),
2599+ ("audience", "assignees"),
2600+ ],
1981 )2601 )
1982 .await;2602 .await;
1983 assert!(answer.body.contains("EmptySubject"), "{}", answer.body);2603 assert!(answer.body.contains("EmptySubject"), "{}", answer.body);
@@ -2002,7 +2622,9 @@ async fn a_rule_may_not_be_hung_off_a_column_that_is_not_on_this_board() {
2002 .await;2622 .await;
2003 assert!(answer.body.contains("Forbidden"), "{}", answer.body);2623 assert!(answer.body.contains("Forbidden"), "{}", answer.body);
2004 2624
2005- let seen = app.post("/api/current_rules", Some(&admin_cookie), &[]).await;2625+ let seen = app
2626+ .post("/api/current_rules", Some(&admin_cookie), &[])
2627+ .await;
2006 assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);2628 assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);
2007 }2629 }
2008 2630
@@ -2016,7 +2638,12 @@ async fn an_audience_the_screen_never_offers_is_refused() {
2016 .post(2638 .post(
2017 "/api/create_rule",2639 "/api/create_rule",
2018 Some(&admin_cookie),2640 Some(&admin_cookie),
2019- &[("trigger", "status"), ("column_id", &column), ("subject", "Task completed"), ("audience", "everyone-everywhere")],2641+ &[
2642+ ("trigger", "status"),
2643+ ("column_id", &column),
2644+ ("subject", "Task completed"),
2645+ ("audience", "everyone-everywhere"),
2646+ ],
2020 )2647 )
2021 .await;2648 .await;
2022 assert!(answer.body.contains("Forbidden"), "{}", answer.body);2649 assert!(answer.body.contains("Forbidden"), "{}", answer.body);
@@ -2030,13 +2657,25 @@ async fn switching_a_rule_off_leaves_it_listed_and_switched_off() {
2030 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);2657 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
2031 let rule = only_rule(&app, &admin_cookie).await;2658 let rule = only_rule(&app, &admin_cookie).await;
2032 2659
2033- let answer = app.post("/api/set_rule_enabled", Some(&admin_cookie), &[("rule_id", &rule), ("enabled", "false")]).await;2660+ let answer = app
2661+ .post(
2662+ "/api/set_rule_enabled",
2663+ Some(&admin_cookie),
2664+ &[("rule_id", &rule), ("enabled", "false")],
2665+ )
2666+ .await;
2034 assert_eq!(answer.body, "null", "{}", answer.body);2667 assert_eq!(answer.body, "null", "{}", answer.body);
2035 2668
2036 // The screen lists what exists, not what is live.2669 // The screen lists what exists, not what is live.
2037- let seen = app.post("/api/current_rules", Some(&admin_cookie), &[]).await;2670+ let seen = app
2671+ .post("/api/current_rules", Some(&admin_cookie), &[])
2672+ .await;
2038 assert!(seen.body.contains("\"enabled\":false"), "{}", seen.body);2673 assert!(seen.body.contains("\"enabled\":false"), "{}", seen.body);
2039- assert!(seen.body.contains("\"subject\":\"Task completed\""), "{}", seen.body);2674+ assert!(
2675+ seen.body.contains("\"subject\":\"Task completed\""),
2676+ "{}",
2677+ seen.body
2678+ );
2040 }2679 }
2041 2680
2042 #[tokio::test]2681 #[tokio::test]
@@ -2046,7 +2685,13 @@ async fn a_rule_id_this_workspace_does_not_own_is_refused() {
2046 let stranger = Ulid::new().to_string();2685 let stranger = Ulid::new().to_string();
2047 2686
2048 for path in ["/api/set_rule_enabled", "/api/delete_rule"] {2687 for path in ["/api/set_rule_enabled", "/api/delete_rule"] {
2049- let answer = app.post(path, Some(&admin_cookie), &[("rule_id", &stranger), ("enabled", "false")]).await;2688+ let answer = app
2689+ .post(
2690+ path,
2691+ Some(&admin_cookie),
2692+ &[("rule_id", &stranger), ("enabled", "false")],
2693+ )
2694+ .await;
2050 assert!(answer.body.contains("NotFound"), "{path}: {}", answer.body);2695 assert!(answer.body.contains("NotFound"), "{path}: {}", answer.body);
2051 }2696 }
2052 }2697 }
@@ -2059,10 +2704,18 @@ async fn deleting_a_rule_takes_it_off_the_screen() {
2059 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);2704 assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
2060 let rule = only_rule(&app, &admin_cookie).await;2705 let rule = only_rule(&app, &admin_cookie).await;
2061 2706
2062- let answer = app.post("/api/delete_rule", Some(&admin_cookie), &[("rule_id", &rule)]).await;2707+ let answer = app
2708+ .post(
2709+ "/api/delete_rule",
2710+ Some(&admin_cookie),
2711+ &[("rule_id", &rule)],
2712+ )
2713+ .await;
2063 assert_eq!(answer.body, "null", "{}", answer.body);2714 assert_eq!(answer.body, "null", "{}", answer.body);
2064 2715
2065- let seen = app.post("/api/current_rules", Some(&admin_cookie), &[]).await;2716+ let seen = app
2717+ .post("/api/current_rules", Some(&admin_cookie), &[])
2718+ .await;
2066 assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);2719 assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);
2067 }2720 }
2068 2721
@@ -2085,22 +2738,41 @@ async fn only_an_admin_may_read_or_write_the_rules() {
2085 .post(2738 .post(
2086 "/api/create_rule",2739 "/api/create_rule",
2087 Some(who),2740 Some(who),
2088- &[("trigger", "status"), ("column_id", &column), ("subject", "Mail everyone about me"), ("audience", "board")],2741+ &[
2742+ ("trigger", "status"),
2743+ ("column_id", &column),
2744+ ("subject", "Mail everyone about me"),
2745+ ("audience", "board"),
2746+ ],
2089 )2747 )
2090 .await;2748 .await;
2091 assert!(written.body.contains("Forbidden"), "{}", written.body);2749 assert!(written.body.contains("Forbidden"), "{}", written.body);
2092 2750
2093- let switched = app.post("/api/set_rule_enabled", Some(who), &[("rule_id", &rule), ("enabled", "false")]).await;2751+ let switched = app
2752+ .post(
2753+ "/api/set_rule_enabled",
2754+ Some(who),
2755+ &[("rule_id", &rule), ("enabled", "false")],
2756+ )
2757+ .await;
2094 assert!(switched.body.contains("Forbidden"), "{}", switched.body);2758 assert!(switched.body.contains("Forbidden"), "{}", switched.body);
2095 2759
2096- let deleted = app.post("/api/delete_rule", Some(who), &[("rule_id", &rule)]).await;2760+ let deleted = app
2761+ .post("/api/delete_rule", Some(who), &[("rule_id", &rule)])
2762+ .await;
2097 assert!(deleted.body.contains("Forbidden"), "{}", deleted.body);2763 assert!(deleted.body.contains("Forbidden"), "{}", deleted.body);
2098 }2764 }
2099 2765
2100 // And the rule is untouched: still there, still on.2766 // And the rule is untouched: still there, still on.
2101- let seen = app.post("/api/current_rules", Some(&admin_cookie), &[]).await;2767+ let seen = app
2768+ .post("/api/current_rules", Some(&admin_cookie), &[])
2769+ .await;
2102 assert!(seen.body.contains("\"enabled\":true"), "{}", seen.body);2770 assert!(seen.body.contains("\"enabled\":true"), "{}", seen.body);
2103- assert!(!seen.body.contains("Mail everyone about me"), "{}", seen.body);2771+ assert!(
2772+ !seen.body.contains("Mail everyone about me"),
2773+ "{}",
2774+ seen.body
2775+ );
2104 }2776 }
2105 2777
2106 #[tokio::test]2778 #[tokio::test]
@@ -2115,13 +2787,25 @@ async fn a_signed_out_browser_may_not_touch_the_rules() {
2115 ("/api/current_rules", vec![] as Vec<(&str, &str)>),2787 ("/api/current_rules", vec![] as Vec<(&str, &str)>),
2116 (2788 (
2117 "/api/create_rule",2789 "/api/create_rule",
2118- vec![("trigger", "status"), ("column_id", column.as_str()), ("subject", "Task completed"), ("audience", "assignees")],2790+ vec![
2791+ ("trigger", "status"),
2792+ ("column_id", column.as_str()),
2793+ ("subject", "Task completed"),
2794+ ("audience", "assignees"),
2795+ ],
2796+ ),
2797+ (
2798+ "/api/set_rule_enabled",
2799+ vec![("rule_id", rule.as_str()), ("enabled", "false")],
2119 ),2800 ),
2120- ("/api/set_rule_enabled", vec![("rule_id", rule.as_str()), ("enabled", "false")]),
2121 ("/api/delete_rule", vec![("rule_id", rule.as_str())]),2801 ("/api/delete_rule", vec![("rule_id", rule.as_str())]),
2122 ] {2802 ] {
2123 let answer = app.post(path, None, &form).await;2803 let answer = app.post(path, None, &form).await;
2124- assert!(answer.body.contains("SignInFirst"), "{path}: {}", answer.body);2804+ assert!(
2805+ answer.body.contains("SignInFirst"),
2806+ "{path}: {}",
2807+ answer.body
2808+ );
2125 }2809 }
2126 }2810 }
2127 2811
@@ -2151,11 +2835,19 @@ async fn the_files_section_is_on_the_detail_page() {
2151 let column = first_column(&app).await;2835 let column = first_column(&app).await;
2152 let task = a_task(&app, &admin_cookie, &column, "Attach something to me").await;2836 let task = a_task(&app, &admin_cookie, &column, "Attach something to me").await;
2153 2837
2154- let page = app.get(&format!("/?task={task}"), Some(&admin_cookie)).await;2838+ let page = app
2839+ .get(&format!("/?task={task}"), Some(&admin_cookie))
2840+ .await;
2155 assert_eq!(page.status, StatusCode::OK);2841 assert_eq!(page.status, StatusCode::OK);
2156 let html = String::from_utf8_lossy(&page.bytes);2842 let html = String::from_utf8_lossy(&page.bytes);
2157- assert!(html.contains("multipart/form-data"), "no multipart upload form on the detail page");2843+ assert!(
2158- assert!(html.contains(r#"action="/files""#), "the upload form does not post to /files");2844+ html.contains("multipart/form-data"),
2845+ "no multipart upload form on the detail page"
2846+ );
2847+ assert!(
2848+ html.contains(r#"action="/files""#),
2849+ "the upload form does not post to /files"
2850+ );
2159 }2851 }
2160 2852
2161 #[tokio::test]2853 #[tokio::test]
@@ -2165,15 +2857,29 @@ async fn the_datepicker_shell_renders_in_both_task_modals() {
2165 let column = first_column(&app).await;2857 let column = first_column(&app).await;
2166 let task = a_task(&app, &admin_cookie, &column, "Pick a date on me").await;2858 let task = a_task(&app, &admin_cookie, &column, "Pick a date on me").await;
2167 2859
2168- let detail = app.get(&format!("/?task={task}"), Some(&admin_cookie)).await;2860+ let detail = app
2861+ .get(&format!("/?task={task}"), Some(&admin_cookie))
2862+ .await;
2169 let html = String::from_utf8_lossy(&detail.bytes);2863 let html = String::from_utf8_lossy(&detail.bytes);
2170- assert!(html.contains("datepick-input"), "no datepicker shell on the task modal: {html}");2864+ assert!(
2171- assert!(html.contains("datepick-grid"), "no datepicker grid on the task modal: {html}");2865+ html.contains("datepick-input"),
2866+ "no datepicker shell on the task modal: {html}"
2867+ );
2868+ assert!(
2869+ html.contains("datepick-grid"),
2870+ "no datepicker grid on the task modal: {html}"
2871+ );
2172 2872
2173 let new_task = app.get("/?new=1", Some(&admin_cookie)).await;2873 let new_task = app.get("/?new=1", Some(&admin_cookie)).await;
2174 let html = String::from_utf8_lossy(&new_task.bytes);2874 let html = String::from_utf8_lossy(&new_task.bytes);
2175- assert!(html.contains("datepick-input"), "no datepicker shell on the new-task modal: {html}");2875+ assert!(
2176- assert!(html.contains("datepick-grid"), "no datepicker grid on the new-task modal: {html}");2876+ html.contains("datepick-input"),
2877+ "no datepicker shell on the new-task modal: {html}"
2878+ );
2879+ assert!(
2880+ html.contains("datepick-grid"),
2881+ "no datepicker grid on the new-task modal: {html}"
2882+ );
2177 }2883 }
2178 2884
2179 /// The id of the file named `name` in a `/api/fetch_task` snapshot's body,2885 /// The id of the file named `name` in a `/api/fetch_task` snapshot's body,
@@ -2196,39 +2902,74 @@ fn attachment_id_named(body: &str, name: &str) -> String {
2196 async fn a_viewer_who_posts_an_upload_anyway_is_refused() {2902 async fn a_viewer_who_posts_an_upload_anyway_is_refused() {
2197 let app = App::open().await;2903 let app = App::open().await;
2198 let admin_cookie = admin(&app).await;2904 let admin_cookie = admin(&app).await;
2199- let viewer = invited(&app, &admin_cookie, "quiet@izlek.sh", "Quiet Reader", Role::Viewer).await;2905+ let viewer = invited(
2906+ &app,
2907+ &admin_cookie,
2908+ "quiet@izlek.sh",
2909+ "Quiet Reader",
2910+ Role::Viewer,
2911+ )
2912+ .await;
2200 let column = first_column(&app).await;2913 let column = first_column(&app).await;
2201 let task = a_task(&app, &admin_cookie, &column, "Viewers cannot attach").await;2914 let task = a_task(&app, &admin_cookie, &column, "Viewers cannot attach").await;
2202 2915
2203 let answer = app2916 let answer = app
2204- .post_multipart("/files", Some(&viewer), &[("task_id", &task)], Some(("note.txt", "text/plain", b"hello")))2917+ .post_multipart(
2918+ "/files",
2919+ Some(&viewer),
2920+ &[("task_id", &task)],
2921+ Some(("note.txt", "text/plain", b"hello")),
2922+ )
2205 .await;2923 .await;
2206 assert_eq!(answer.status, StatusCode::SEE_OTHER);2924 assert_eq!(answer.status, StatusCode::SEE_OTHER);
2207- assert_eq!(answer.location.as_deref(), Some("/?refusal=forbidden&on=upload_file"));2925+ assert_eq!(
2926+ answer.location.as_deref(),
2927+ Some("/?refusal=forbidden&on=upload_file")
2928+ );
2208 }2929 }
2209 2930
2210 #[tokio::test]2931 #[tokio::test]
2211 async fn a_member_uploads_a_file_and_the_chip_comes_back() {2932 async fn a_member_uploads_a_file_and_the_chip_comes_back() {
2212 let app = App::open().await;2933 let app = App::open().await;
2213 let admin_cookie = admin(&app).await;2934 let admin_cookie = admin(&app).await;
2214- let member = invited(&app, &admin_cookie, "mo@izlek.sh", "Mo Dubois", Role::Member).await;2935+ let member = invited(
2936+ &app,
2937+ &admin_cookie,
2938+ "mo@izlek.sh",
2939+ "Mo Dubois",
2940+ Role::Member,
2941+ )
2942+ .await;
2215 let column = first_column(&app).await;2943 let column = first_column(&app).await;
2216 let task = a_task(&app, &admin_cookie, &column, "Attach the spec").await;2944 let task = a_task(&app, &admin_cookie, &column, "Attach the spec").await;
2217 2945
2218 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];2946 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
2219 let answer = app2947 let answer = app
2220- .post_multipart("/files", Some(&member), &[("task_id", &task)], Some(("spec.png", "image/png", &png)))2948+ .post_multipart(
2949+ "/files",
2950+ Some(&member),
2951+ &[("task_id", &task)],
2952+ Some(("spec.png", "image/png", &png)),
2953+ )
2221 .await;2954 .await;
2222 assert_eq!(answer.status, StatusCode::SEE_OTHER);2955 assert_eq!(answer.status, StatusCode::SEE_OTHER);
2223- assert_eq!(answer.location.as_deref(), Some(format!("/?task={task}").as_str()));2956+ assert_eq!(
2957+ answer.location.as_deref(),
2958+ Some(format!("/?task={task}").as_str())
2959+ );
2224 2960
2225- let snapshot = app.post("/api/fetch_task", Some(&member), &[("task_id", &task)]).await;2961+ let snapshot = app
2962+ .post("/api/fetch_task", Some(&member), &[("task_id", &task)])
2963+ .await;
2226 let file_id = attachment_id_named(&snapshot.body, "spec.png");2964 let file_id = attachment_id_named(&snapshot.body, "spec.png");
2227 2965
2228 let page = app.get(&format!("/?task={task}"), Some(&member)).await;2966 let page = app.get(&format!("/?task={task}"), Some(&member)).await;
2229 assert_eq!(page.status, StatusCode::OK);2967 assert_eq!(page.status, StatusCode::OK);
2230 let html = String::from_utf8_lossy(&page.bytes);2968 let html = String::from_utf8_lossy(&page.bytes);
2231- assert!(html.contains(&format!("task={task}&amp;file={file_id}")), "no viewer href for the new file: {html}");2969+ assert!(
2970+ html.contains(&format!("task={task}&amp;file={file_id}")),
2971+ "no viewer href for the new file: {html}"
2972+ );
2232 assert!(html.contains("spec.png"));2973 assert!(html.contains("spec.png"));
2233 2974
2234 let download = app.get(&format!("/files/{file_id}"), Some(&member)).await;2975 let download = app.get(&format!("/files/{file_id}"), Some(&member)).await;
@@ -2244,26 +2985,55 @@ async fn an_image_downloads_inline_and_an_unrecognised_type_stays_attachment() {
2244 let task = a_task(&app, &admin_cookie, &column, "Two kinds of file").await;2985 let task = a_task(&app, &admin_cookie, &column, "Two kinds of file").await;
2245 2986
2246 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];2987 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
2247- app.post_multipart("/files", Some(&admin_cookie), &[("task_id", &task)], Some(("spec.png", "image/png", &png))).await;2988+ app.post_multipart(
2989+ "/files",
2990+ Some(&admin_cookie),
2991+ &[("task_id", &task)],
2992+ Some(("spec.png", "image/png", &png)),
2993+ )
2994+ .await;
2248 let unknown = [0x00u8, 0x01, 0xFE, 0xFF, 0x02];2995 let unknown = [0x00u8, 0x01, 0xFE, 0xFF, 0x02];
2249- app.post_multipart("/files", Some(&admin_cookie), &[("task_id", &task)], Some(("blob.bin", "application/octet-stream", &unknown)))2996+ app.post_multipart(
2250- .await;2997+ "/files",
2998+ Some(&admin_cookie),
2999+ &[("task_id", &task)],
3000+ Some(("blob.bin", "application/octet-stream", &unknown)),
3001+ )
3002+ .await;
2251 3003
2252- let snapshot = app.post("/api/fetch_task", Some(&admin_cookie), &[("task_id", &task)]).await;3004+ let snapshot = app
3005+ .post(
3006+ "/api/fetch_task",
3007+ Some(&admin_cookie),
3008+ &[("task_id", &task)],
3009+ )
3010+ .await;
2253 let png_id = attachment_id_named(&snapshot.body, "spec.png");3011 let png_id = attachment_id_named(&snapshot.body, "spec.png");
2254 let blob_id = attachment_id_named(&snapshot.body, "blob.bin");3012 let blob_id = attachment_id_named(&snapshot.body, "blob.bin");
2255 3013
2256- let png_download = app.get(&format!("/files/{png_id}"), Some(&admin_cookie)).await;3014+ let png_download = app
3015+ .get(&format!("/files/{png_id}"), Some(&admin_cookie))
3016+ .await;
2257 assert_eq!(png_download.content_type.as_deref(), Some("image/png"));3017 assert_eq!(png_download.content_type.as_deref(), Some("image/png"));
2258 assert!(3018 assert!(
2259- png_download.disposition.as_deref().unwrap_or_default().starts_with("inline;"),3019+ png_download
3020+ .disposition
3021+ .as_deref()
3022+ .unwrap_or_default()
3023+ .starts_with("inline;"),
2260 "{:?}",3024 "{:?}",
2261 png_download.disposition3025 png_download.disposition
2262 );3026 );
2263 3027
2264- let blob_download = app.get(&format!("/files/{blob_id}"), Some(&admin_cookie)).await;3028+ let blob_download = app
3029+ .get(&format!("/files/{blob_id}"), Some(&admin_cookie))
3030+ .await;
2265 assert!(3031 assert!(
2266- blob_download.disposition.as_deref().unwrap_or_default().starts_with("attachment;"),3032+ blob_download
3033+ .disposition
3034+ .as_deref()
3035+ .unwrap_or_default()
3036+ .starts_with("attachment;"),
2267 "{:?}",3037 "{:?}",
2268 blob_download.disposition3038 blob_download.disposition
2269 );3039 );
@@ -2277,13 +3047,31 @@ async fn dl_forces_a_download_of_an_otherwise_inline_type() {
2277 let task = a_task(&app, &admin_cookie, &column, "Forced download").await;3047 let task = a_task(&app, &admin_cookie, &column, "Forced download").await;
2278 3048
2279 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];3049 let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
2280- app.post_multipart("/files", Some(&admin_cookie), &[("task_id", &task)], Some(("spec.png", "image/png", &png))).await;3050+ app.post_multipart(
2281- let snapshot = app.post("/api/fetch_task", Some(&admin_cookie), &[("task_id", &task)]).await;3051+ "/files",
3052+ Some(&admin_cookie),
3053+ &[("task_id", &task)],
3054+ Some(("spec.png", "image/png", &png)),
3055+ )
3056+ .await;
3057+ let snapshot = app
3058+ .post(
3059+ "/api/fetch_task",
3060+ Some(&admin_cookie),
3061+ &[("task_id", &task)],
3062+ )
3063+ .await;
2282 let file_id = attachment_id_named(&snapshot.body, "spec.png");3064 let file_id = attachment_id_named(&snapshot.body, "spec.png");
2283 3065
2284- let forced = app.get(&format!("/files/{file_id}?dl=1"), Some(&admin_cookie)).await;3066+ let forced = app
3067+ .get(&format!("/files/{file_id}?dl=1"), Some(&admin_cookie))
3068+ .await;
2285 assert!(3069 assert!(
2286- forced.disposition.as_deref().unwrap_or_default().starts_with("attachment;"),3070+ forced
3071+ .disposition
3072+ .as_deref()
3073+ .unwrap_or_default()
3074+ .starts_with("attachment;"),
2287 "{:?}",3075 "{:?}",
style/main.scssmodified+13 -0
@@ -935,6 +935,19 @@ a {
935 &-tone-4 { background: var(--avatar-tone-4); }935 &-tone-4 { background: var(--avatar-tone-4); }
936 }936 }
937 937
938+// A photo avatar is the same box with the picture where the tone fill was;
939+// size and shape ride the shared .avatar classes.
940+img.avatar {
941+ object-fit: cover;
942+ display: block;
943+}
944+
945+.photo-row {
946+ display: flex;
947+ align-items: center;
948+ gap: 12px;
949+}
950+
938 // -- the card context menu ---------------------------------------------------951 // -- the card context menu ---------------------------------------------------
939 //952 //
940 // A right-click opens this at the cursor; `card_menu_script` (board.rs) sets953 // A right-click opens this at the cursor; `card_menu_script` (board.rs) sets