Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Use real social wall data and links

Anand Baburajan70e50010f397
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rs
index 2d718b1113..3a38184e92 100644
--- a/rust/wall/src/client.rs
+++ b/rust/wall/src/client.rs
@@ -1,10 +1,10 @@
use std::collections::BTreeMap;
use crate::crypto::{
- decode_b64, decode_b64_url, decrypt_entity_key, decrypt_secretbox_packed,
- derive_wall_link_auth_key, derive_wall_link_wrap_key, encode_b64, encode_b64_url,
- encrypt_asset_payload, encrypt_entity_key, encrypt_secretbox_packed, generate_key,
- pack_payload, unpack_payload,
+ decode_b64, decrypt_entity_key, decrypt_secretbox_packed, derive_wall_link_auth_key,
+ derive_wall_link_wrap_key, encode_b64, encrypt_asset_payload, encrypt_entity_key,
+ encrypt_secretbox_packed, generate_key, generate_wall_link_access_key, pack_payload,
+ unpack_payload, wall_link_access_key_material,
};
use crate::error::{Result, WallError};
use crate::models::{
@@ -920,9 +920,10 @@ impl AccountWallCtx {
.ok_or_else(|| {
WallError::InvalidInput(format!("wall {wall_id} is not owned by the account"))
})?;
- let access_key = generate_key();
- let auth_key = derive_wall_link_auth_key(&access_key)?;
- let wrap_key = derive_wall_link_wrap_key(&access_key)?;
+ let access_key = generate_wall_link_access_key();
+ let access_key_material = wall_link_access_key_material(&access_key)?;
+ let auth_key = derive_wall_link_auth_key(&access_key_material)?;
+ let wrap_key = derive_wall_link_wrap_key(&access_key_material)?;
let request = WallLinkCreateRequest {
wall_id: wall_id.to_owned(),
auth_key: encode_b64(&auth_key),
@@ -931,7 +932,7 @@ impl AccountWallCtx {
};
let status: WallLinkStatusResponse = self.client.post_json("/wall/links", &request).await?;
Ok(CreatedWallLink {
- access_key: encode_b64_url(&access_key),
+ access_key,
wall_username: status.wall_slug.clone(),
wall_id: wall_id.to_owned(),
wall_slug: status.wall_slug,
@@ -1021,9 +1022,9 @@ fn post_response_from_feed_item(item: &FeedItem) -> PostResponse {
impl WallLinkCtx {
pub async fn open(input: OpenWallLinkCtxInput) -> Result<Self> {
- let access_key = decode_b64_url(&input.access_key)?;
- let auth_key = derive_wall_link_auth_key(&access_key)?;
- let wrap_key = derive_wall_link_wrap_key(&access_key)?;
+ let access_key_material = wall_link_access_key_material(&input.access_key)?;
+ let auth_key = derive_wall_link_auth_key(&access_key_material)?;
+ let wrap_key = derive_wall_link_wrap_key(&access_key_material)?;
let client = build_http_client(
&input.base_url,
None,
@@ -1309,6 +1310,7 @@ fn decrypt_wall_profile(
wall_id: profile.wall_id.clone(),
wall_slug: profile.wall_slug.clone(),
version: profile.version,
+ friends: profile.friends,
profile: profile_bytes,
avatar: profile.avatar.clone(),
updated_at: if profile.updated_at.is_empty() {
@@ -1443,9 +1445,11 @@ mod tests {
async fn wall_link_open_decrypts_current_wall_key() {
let mut server = Server::new_async().await;
let wall_key = generate_key();
- let access_key = generate_key();
- let auth_key = derive_wall_link_auth_key(&access_key).expect("auth key");
- let wrap_key = derive_wall_link_wrap_key(&access_key).expect("wrap key");
+ let access_key = "AbC123xYz789";
+ let access_key_material =
+ wall_link_access_key_material(access_key).expect("access key material");
+ let auth_key = derive_wall_link_auth_key(&access_key_material).expect("auth key");
+ let wrap_key = derive_wall_link_wrap_key(&access_key_material).expect("wrap key");
let encrypted_wall_key = encode_b64(
&encrypt_secretbox_packed(&wrap_key, &wall_key).expect("encrypted wall key"),
);
@@ -1492,7 +1496,7 @@ mod tests {
let ctx = WallLinkCtx::open(OpenWallLinkCtxInput {
base_url: server.url(),
wall_username: "@owner-gallery".to_owned(),
- access_key: encode_b64_url(&access_key),
+ access_key: access_key.to_owned(),
user_agent: None,
client_package: None,
client_version: None,
@@ -1512,10 +1516,16 @@ mod tests {
async fn wall_link_open_rejects_wrong_access_key() {
let mut server = Server::new_async().await;
let wall_key = generate_key();
- let correct_access_key = generate_key();
- let wrong_access_key = generate_key();
- let wrong_auth_key = derive_wall_link_auth_key(&wrong_access_key).expect("auth key");
- let correct_wrap_key = derive_wall_link_wrap_key(&correct_access_key).expect("wrap key");
+ let correct_access_key = "CorrectKey12";
+ let wrong_access_key = "WrongKey1234";
+ let correct_access_key_material =
+ wall_link_access_key_material(correct_access_key).expect("correct access key material");
+ let wrong_access_key_material =
+ wall_link_access_key_material(wrong_access_key).expect("wrong access key material");
+ let wrong_auth_key =
+ derive_wall_link_auth_key(&wrong_access_key_material).expect("auth key");
+ let correct_wrap_key =
+ derive_wall_link_wrap_key(&correct_access_key_material).expect("wrap key");
let encrypted_wall_key = encode_b64(
&encrypt_secretbox_packed(&correct_wrap_key, &wall_key).expect("encrypted wall key"),
);
@@ -1561,7 +1571,7 @@ mod tests {
let err = match WallLinkCtx::open(OpenWallLinkCtxInput {
base_url: server.url(),
wall_username: "owner-gallery".to_owned(),
- access_key: encode_b64_url(&wrong_access_key),
+ access_key: wrong_access_key.to_owned(),
user_agent: None,
client_package: None,
client_version: None,
@@ -2004,6 +2014,7 @@ mod tests {
"wallId": "wall_owner_main",
"wallSlug": "owner-main",
"version": 3,
+ "friends": 2,
"encryptedProfile": encrypted_profile,
"updatedAt": "2026-04-16T00:00:00Z"
})
@@ -2044,6 +2055,7 @@ mod tests {
assert_eq!(decrypted.wall_id, "wall_owner_main");
assert_eq!(decrypted.wall_slug, "owner-main");
assert_eq!(decrypted.version, 3);
+ assert_eq!(decrypted.friends, 2);
assert_eq!(decrypted.profile, b"profile-json");
profile.assert_async().await;
entity.assert_async().await;
@@ -2552,6 +2564,13 @@ mod tests {
assert!(status_response.active);
assert_eq!(created.wall_id, "wall_owner_main");
assert_eq!(created.wall_username, "owner-main");
+ assert_eq!(created.access_key.len(), 12);
+ assert!(
+ created
+ .access_key
+ .bytes()
+ .all(|value| value.is_ascii_alphanumeric())
+ );
assert_eq!(created.key_version, 3);
status.assert_async().await;
entity.assert_async().await;
diff --git a/rust/wall/src/crypto.rs b/rust/wall/src/crypto.rs
index de570528a9..99e8492ee2 100644
--- a/rust/wall/src/crypto.rs
+++ b/rust/wall/src/crypto.rs
@@ -1,32 +1,59 @@
-use base64::{
- Engine,
- engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
-};
-use ente_core::crypto::{kdf, keys, secretbox};
+use base64::{Engine, engine::general_purpose::STANDARD};
+use ente_core::crypto::{hash, kdf, keys, secretbox};
use crate::error::{Result, WallError};
use crate::transport::EntityKeyPayload;
pub const SECRETBOX_NONCE_BYTES: usize = secretbox::NONCE_BYTES;
+const WALL_LINK_ACCESS_KEY_LEN: usize = 12;
+const WALL_LINK_ACCESS_KEY_ALPHABET: &[u8] =
+ b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
pub fn generate_key() -> Vec<u8> {
keys::generate_key_secure().into_vec()
}
-pub fn encode_b64(bytes: &[u8]) -> String {
- STANDARD.encode(bytes)
+pub fn generate_wall_link_access_key() -> String {
+ let max_unbiased_value = 256 - (256 % WALL_LINK_ACCESS_KEY_ALPHABET.len());
+ let mut out = String::with_capacity(WALL_LINK_ACCESS_KEY_LEN);
+
+ while out.len() < WALL_LINK_ACCESS_KEY_LEN {
+ for value in generate_key() {
+ if usize::from(value) >= max_unbiased_value {
+ continue;
+ }
+ out.push(char::from(
+ WALL_LINK_ACCESS_KEY_ALPHABET
+ [usize::from(value) % WALL_LINK_ACCESS_KEY_ALPHABET.len()],
+ ));
+ if out.len() == WALL_LINK_ACCESS_KEY_LEN {
+ break;
+ }
+ }
+ }
+
+ out
}
-pub fn decode_b64(value: &str) -> Result<Vec<u8>> {
- Ok(STANDARD.decode(value.trim())?)
+pub fn wall_link_access_key_material(access_key: &str) -> Result<Vec<u8>> {
+ let trimmed = access_key.trim();
+ let is_base62 = trimmed
+ .bytes()
+ .all(|value| WALL_LINK_ACCESS_KEY_ALPHABET.contains(&value));
+ if trimmed.len() != WALL_LINK_ACCESS_KEY_LEN || !is_base62 {
+ return Err(WallError::InvalidInput(
+ "invalid wall link access key".into(),
+ ));
+ }
+ hash::hash_default(trimmed.as_bytes()).map_err(Into::into)
}
-pub fn encode_b64_url(bytes: &[u8]) -> String {
- URL_SAFE_NO_PAD.encode(bytes)
+pub fn encode_b64(bytes: &[u8]) -> String {
+ STANDARD.encode(bytes)
}
-pub fn decode_b64_url(value: &str) -> Result<Vec<u8>> {
- Ok(URL_SAFE_NO_PAD.decode(value.trim())?)
+pub fn decode_b64(value: &str) -> Result<Vec<u8>> {
+ Ok(STANDARD.decode(value.trim())?)
}
pub fn derive_wall_link_auth_key(access_key: &[u8]) -> Result<Vec<u8>> {
@@ -144,6 +171,26 @@ mod tests {
assert_ne!(auth_key, wrap_key);
}
+ #[test]
+ fn wall_link_access_key_is_short_base62() {
+ let access_key = generate_wall_link_access_key();
+ assert_eq!(access_key.len(), 12);
+ assert!(
+ access_key
+ .bytes()
+ .all(|value| value.is_ascii_alphanumeric())
+ );
+
+ let material = wall_link_access_key_material(&access_key).unwrap();
+ assert_eq!(material.len(), 32);
+ }
+
+ #[test]
+ fn wall_link_access_key_rejects_legacy_b64_url_key() {
+ let old_key = "LqUerMGZjrvdfkd6TayOiDa9pM0pYeGcakjhhsB47Hc";
+ assert!(wall_link_access_key_material(old_key).is_err());
+ }
+
#[test]
fn wall_link_key_derivation_matches_vector() {
let access_key = vec![0; 32];
diff --git a/rust/wall/src/models.rs b/rust/wall/src/models.rs
index 38099ea9c1..62452d2eb9 100644
--- a/rust/wall/src/models.rs
+++ b/rust/wall/src/models.rs
@@ -68,6 +68,7 @@ pub struct DecryptedWallProfile {
pub wall_id: String,
pub wall_slug: String,
pub version: i32,
+ pub friends: i64,
pub profile: Vec<u8>,
pub avatar: Option<ProfileAvatarResponse>,
pub updated_at: Option<String>,
diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rs
index 9b1a66da4b..0834b6f94c 100644
--- a/rust/wall/src/transport.rs
+++ b/rust/wall/src/transport.rs
@@ -268,6 +268,8 @@ pub struct WallProfileResponse {
pub wall_slug: String,
pub version: i32,
#[serde(default)]
+ pub friends: i64,
+ #[serde(default)]
pub encrypted_profile: String,
#[serde(default)]
pub updated_at: String,
diff --git a/server/migrations/122_wall_multiple_links.down.sql b/server/migrations/122_wall_multiple_links.down.sql
new file mode 100644
index 0000000000..d91f7f0f6a
--- /dev/null
+++ b/server/migrations/122_wall_multiple_links.down.sql
@@ -0,0 +1,17 @@
+DELETE FROM wall_link_sessions;
+
+DELETE FROM wall_links existing
+USING wall_links newer
+WHERE existing.wall_id = newer.wall_id
+ AND (
+ existing.updated_at < newer.updated_at
+ OR (existing.updated_at = newer.updated_at AND existing.auth_key_hash < newer.auth_key_hash)
+ );
+
+DROP INDEX IF EXISTS idx_wall_links_wall_updated;
+
+ALTER TABLE wall_links
+ DROP CONSTRAINT IF EXISTS wall_links_pkey;
+
+ALTER TABLE wall_links
+ ADD PRIMARY KEY (wall_id);
diff --git a/server/migrations/122_wall_multiple_links.up.sql b/server/migrations/122_wall_multiple_links.up.sql
new file mode 100644
index 0000000000..b382ffadb7
--- /dev/null
+++ b/server/migrations/122_wall_multiple_links.up.sql
@@ -0,0 +1,8 @@
+ALTER TABLE wall_links
+ DROP CONSTRAINT IF EXISTS wall_links_pkey;
+
+ALTER TABLE wall_links
+ ADD PRIMARY KEY (wall_id, auth_key_hash);
+
+CREATE INDEX IF NOT EXISTS idx_wall_links_wall_updated
+ ON wall_links (wall_id, updated_at DESC);
diff --git a/server/wall/controller/walls.go b/server/wall/controller/walls.go
index 2cc7ccfa8b..1315c9ec48 100644
--- a/server/wall/controller/walls.go
+++ b/server/wall/controller/walls.go
@@ -60,6 +60,14 @@ func (c *WallsController) GetProfile(ctx *gin.Context, req models.GetWallProfile
if err := c.auth.canViewWall(ctx.Request.Context(), viewer, wall); err != nil {
return nil, err
}
+ friendsCount := int64(0)
+ if c.auth.FriendsRepo != nil {
+ var err error
+ friendsCount, err = c.auth.FriendsRepo.CountFriendsForWall(ctx.Request.Context(), wall.WallID)
+ if err != nil {
+ return nil, err
+ }
+ }
if req.Version != nil {
if *req.Version <= 0 {
return nil, ente.NewBadRequestWithMessage("invalid version")
@@ -75,6 +83,7 @@ func (c *WallsController) GetProfile(ctx *gin.Context, req models.GetWallProfile
Version: version.Version,
EncryptedProfile: version.EncryptedProfile,
UpdatedAt: formatMicros(version.CreatedAt),
+ Friends: friendsCount,
}, nil
}
}
@@ -85,6 +94,7 @@ func (c *WallsController) GetProfile(ctx *gin.Context, req models.GetWallProfile
EncryptedProfile: wall.EncryptedProfile,
UpdatedAt: formatMicros(wall.UpdatedAt),
Avatar: toAvatarResponse(wall),
+ Friends: friendsCount,
}, nil
}
diff --git a/server/wall/controller/walls_test.go b/server/wall/controller/walls_test.go
index aa39560b72..3735e8ce97 100644
--- a/server/wall/controller/walls_test.go
+++ b/server/wall/controller/walls_test.go
@@ -37,6 +37,28 @@ func TestGetProfileReturnsHistoricalVersion(t *testing.T) {
require.Nil(t, resp.Avatar)
}
+func TestGetProfileIncludesFriendsCount(t *testing.T) {
+ module, repos, userAuthRepo, ctx := setupWallAuthControllerTest(t)
+ aliceID := insertWallControllerUser(t, repos, "[email protected]", "alice-public")
+ bobID := insertWallControllerUser(t, repos, "[email protected]", "bob-public")
+ aliceWall, err := repos.Walls.CreateWall(ctx, aliceID, "alice-friends", "alice-wall-key", "alice-profile")
+ require.NoError(t, err)
+ bobWall, err := repos.Walls.CreateWall(ctx, bobID, "bob-friends", "bob-wall-key", "bob-profile")
+ require.NoError(t, err)
+ require.NoError(t, repos.Friends.AddFriend(ctx, aliceID, aliceWall.WallID, bobWall.WallID, "bob-share-key", bobWall.CurrentVersion, "alice-share-key", aliceWall.CurrentVersion))
+ require.NoError(t, userAuthRepo.AddToken(aliceID, ente.Photos, "alice-friends-token", "127.0.0.1", "wall-test"))
+ ginCtx := newPublicWallContext()
+ ginCtx.Request.Header.Set("X-Auth-Token", "alice-friends-token")
+
+ resp, err := module.Walls.GetProfile(ginCtx, models.GetWallProfileRequest{
+ WallID: aliceWall.WallID,
+ })
+
+ require.NoError(t, err)
+ require.NotNil(t, resp)
+ require.EqualValues(t, 1, resp.Friends)
+}
+
func TestGetProfileRejectsInvalidVersion(t *testing.T) {
module, repos, userAuthRepo, ctx := setupWallAuthControllerTest(t)
aliceID := insertWallControllerUser(t, repos, "[email protected]", "alice-public")
diff --git a/server/wall/models/models.go b/server/wall/models/models.go
index e7ba58ae1e..5020b9da3c 100644
--- a/server/wall/models/models.go
+++ b/server/wall/models/models.go
@@ -176,6 +176,7 @@ type WallProfileResponse struct {
EncryptedProfile string `json:"encryptedProfile,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"`
Avatar *ProfileAvatarResponse `json:"avatar,omitempty"`
+ Friends int64 `json:"friends"`
}
type UpdateWallSlugRequest struct {
diff --git a/server/wall/repo/friends.go b/server/wall/repo/friends.go
index aad724c402..29fc21b0ff 100644
--- a/server/wall/repo/friends.go
+++ b/server/wall/repo/friends.go
@@ -265,6 +265,18 @@ func (r *FriendsRepository) ListFriendsForWall(ctx context.Context, wallID strin
return out, stacktrace.Propagate(rows.Err(), "")
}
+func (r *FriendsRepository) CountFriendsForWall(ctx context.Context, wallID string) (int64, error) {
+ var count int64
+ if err := r.DB.QueryRowContext(ctx, `
+ SELECT COUNT(*)
+ FROM wall_friend_shares
+ WHERE wall_id = $1
+ `, wallID).Scan(&count); err != nil {
+ return 0, stacktrace.Propagate(err, "")
+ }
+ return count, nil
+}
+
func (r *FriendsRepository) ListAccessibleWallIDs(ctx context.Context, viewerID int64, wallIDs []string) (map[string]bool, error) {
out := make(map[string]bool, len(wallIDs))
if viewerID <= 0 || len(wallIDs) == 0 {
diff --git a/server/wall/repo/links.go b/server/wall/repo/links.go
index d2ffadea7e..c27d6ca28f 100644
--- a/server/wall/repo/links.go
+++ b/server/wall/repo/links.go
@@ -27,15 +27,11 @@ func (r *LinksRepository) UpsertLink(ctx context.Context, wallID string, authKey
if currentVersion != keyVersion {
return nil, sql.ErrNoRows
}
- if _, err := tx.ExecContext(ctx, `DELETE FROM wall_link_sessions WHERE wall_id = $1`, wallID); err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
link, err := scanLinkRecord(tx.QueryRowContext(ctx, `
INSERT INTO wall_links (wall_id, auth_key_hash, key_version, encrypted_wall_key, active)
VALUES ($1, $2, $3, $4, TRUE)
- ON CONFLICT (wall_id) DO UPDATE
- SET auth_key_hash = EXCLUDED.auth_key_hash,
- key_version = EXCLUDED.key_version,
+ ON CONFLICT (wall_id, auth_key_hash) DO UPDATE
+ SET key_version = EXCLUDED.key_version,
encrypted_wall_key = EXCLUDED.encrypted_wall_key,
active = TRUE
RETURNING wall_id, $5::text, $6::bigint, $5::text, auth_key_hash, key_version, encrypted_wall_key, active, created_at, updated_at
@@ -54,7 +50,9 @@ func (r *LinksRepository) GetLink(ctx context.Context, wallID string) (*WallLink
SELECT l.wall_id, w.wall_slug, w.owner_id, w.wall_slug, l.auth_key_hash, l.key_version, l.encrypted_wall_key, l.active, l.created_at, l.updated_at
FROM wall_links l
JOIN walls w ON w.wall_id = l.wall_id
- WHERE l.wall_id = $1
+ WHERE l.wall_id = $1 AND l.active = TRUE
+ ORDER BY l.updated_at DESC
+ LIMIT 1
`, wallID))
}
diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.go
index c1fd9509a8..e0c79ccb0b 100644
--- a/server/wall/repo/module_test.go
+++ b/server/wall/repo/module_test.go
@@ -251,13 +251,18 @@ func TestWallModuleLifecycle(t *testing.T) {
newLink, err := module.Links.UpsertLink(ctx, aliceWall.WallID, []byte("new-hash"), rotatedWall.CurrentVersion, "new-wall-link-key")
require.NoError(t, err)
- _, err = module.Links.GetSession(ctx, []byte("token-hash"))
- require.Error(t, err)
+ session, err = module.Links.GetSession(ctx, []byte("token-hash"))
+ require.NoError(t, err)
+ require.Equal(t, link.AuthKeyHash, session.AuthKeyHash)
- err = module.Links.CreateSession(ctx, []byte("token-hash"), newLink.WallID, newLink.AuthKeyHash, newLink.KeyVersion, timeutil.NMinFromNow(30))
+ err = module.Links.CreateSession(ctx, []byte("new-token-hash"), newLink.WallID, newLink.AuthKeyHash, newLink.KeyVersion, timeutil.NMinFromNow(30))
require.NoError(t, err)
err = module.Links.DeleteLink(ctx, aliceWall.WallID)
require.NoError(t, err)
+ _, err = module.Links.GetSession(ctx, []byte("token-hash"))
+ require.Error(t, err)
+ _, err = module.Links.GetSession(ctx, []byte("new-token-hash"))
+ require.Error(t, err)
lookup, err := module.Walls.GetWallBySlug(ctx, "alice")
require.NoError(t, err)
@@ -569,7 +574,7 @@ func TestGetVersionReturnsHistoricalProfile(t *testing.T) {
require.Equal(t, "alice-profile-v2", v2.EncryptedProfile)
}
-func TestCreateSessionRejectsStaleLinkAuthHash(t *testing.T) {
+func TestCreateSessionAcceptsMultipleActiveLinkAuthHashes(t *testing.T) {
ctx := context.Background()
module := newWallTestModule(t)
@@ -582,12 +587,16 @@ func TestCreateSessionRejectsStaleLinkAuthHash(t *testing.T) {
newLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key")
require.NoError(t, err)
- err = module.Links.CreateSession(ctx, []byte("stale-token"), oldLink.WallID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
- require.Error(t, err)
+ err = module.Links.CreateSession(ctx, []byte("old-token"), oldLink.WallID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
+ require.NoError(t, err)
+ session, err := module.Links.GetSession(ctx, []byte("old-token"))
+ require.NoError(t, err)
+ require.Equal(t, oldLink.KeyVersion, session.KeyVersion)
+ require.Equal(t, oldLink.AuthKeyHash, session.AuthKeyHash)
err = module.Links.CreateSession(ctx, []byte("fresh-token"), newLink.WallID, newLink.AuthKeyHash, newLink.KeyVersion, timeutil.NMinFromNow(30))
require.NoError(t, err)
- session, err := module.Links.GetSession(ctx, []byte("fresh-token"))
+ session, err = module.Links.GetSession(ctx, []byte("fresh-token"))
require.NoError(t, err)
require.Equal(t, newLink.KeyVersion, session.KeyVersion)
require.Equal(t, newLink.AuthKeyHash, session.AuthKeyHash)
@@ -609,10 +618,11 @@ func TestGetSessionRejectsStaleLinkMetadata(t *testing.T) {
_, err = module.Links.DB.Exec(`
INSERT INTO wall_link_sessions (token_hash, wall_id, owner_id, auth_key_hash, key_version, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
- `, []byte("stale-auth-token"), oldLink.WallID, oldLink.OwnerID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
+ `, []byte("old-auth-token"), oldLink.WallID, oldLink.OwnerID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
require.NoError(t, err)
- _, err = module.Links.GetSession(ctx, []byte("stale-auth-token"))
- require.Error(t, err)
+ session, err := module.Links.GetSession(ctx, []byte("old-auth-token"))
+ require.NoError(t, err)
+ require.Equal(t, oldLink.AuthKeyHash, session.AuthKeyHash)
rotatedWall, err := module.Walls.RotateKey(ctx, aliceID, wall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)
require.NoError(t, err)
diff --git a/web/apps/social/public/images/sample-avatar.jpg b/web/apps/social/public/images/sample-avatar.jpg
deleted file mode 100644
index c054f50b44..0000000000
Binary files a/web/apps/social/public/images/sample-avatar.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-1.jpg b/web/apps/social/public/images/sample-feed-1.jpg
deleted file mode 100644
index ac4f49e874..0000000000
Binary files a/web/apps/social/public/images/sample-feed-1.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-2.jpg b/web/apps/social/public/images/sample-feed-2.jpg
deleted file mode 100644
index 37899c8ce9..0000000000
Binary files a/web/apps/social/public/images/sample-feed-2.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-3.jpg b/web/apps/social/public/images/sample-feed-3.jpg
deleted file mode 100644
index 24cb37607e..0000000000
Binary files a/web/apps/social/public/images/sample-feed-3.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-4.jpg b/web/apps/social/public/images/sample-feed-4.jpg
deleted file mode 100644
index 1ebdbd3acd..0000000000
Binary files a/web/apps/social/public/images/sample-feed-4.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-5.jpg b/web/apps/social/public/images/sample-feed-5.jpg
deleted file mode 100644
index f47ebbf577..0000000000
Binary files a/web/apps/social/public/images/sample-feed-5.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-6.jpg b/web/apps/social/public/images/sample-feed-6.jpg
deleted file mode 100644
index 4d146de3c2..0000000000
Binary files a/web/apps/social/public/images/sample-feed-6.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-portrait-1.jpg b/web/apps/social/public/images/sample-feed-portrait-1.jpg
deleted file mode 100644
index efbbfebf24..0000000000
Binary files a/web/apps/social/public/images/sample-feed-portrait-1.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-portrait-2.jpg b/web/apps/social/public/images/sample-feed-portrait-2.jpg
deleted file mode 100644
index f2fd34cae5..0000000000
Binary files a/web/apps/social/public/images/sample-feed-portrait-2.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-portrait-3.jpg b/web/apps/social/public/images/sample-feed-portrait-3.jpg
deleted file mode 100644
index 1184cb9e9e..0000000000
Binary files a/web/apps/social/public/images/sample-feed-portrait-3.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-portrait-4.jpg b/web/apps/social/public/images/sample-feed-portrait-4.jpg
deleted file mode 100644
index 2bd1c13306..0000000000
Binary files a/web/apps/social/public/images/sample-feed-portrait-4.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-portrait-5.jpg b/web/apps/social/public/images/sample-feed-portrait-5.jpg
deleted file mode 100644
index 7cb1ea5d82..0000000000
Binary files a/web/apps/social/public/images/sample-feed-portrait-5.jpg and /dev/null differ
diff --git a/web/apps/social/public/images/sample-feed-portrait-6.jpg b/web/apps/social/public/images/sample-feed-portrait-6.jpg
deleted file mode 100644
index 3066a41845..0000000000
Binary files a/web/apps/social/public/images/sample-feed-portrait-6.jpg and /dev/null differ
diff --git a/web/apps/social/src/components/SocialFileViewer.tsx b/web/apps/social/src/components/SocialFileViewer.tsx
index 706b4b1077..cc476ed3b1 100644
--- a/web/apps/social/src/components/SocialFileViewer.tsx
+++ b/web/apps/social/src/components/SocialFileViewer.tsx
@@ -53,11 +53,6 @@ const postButtonSpin = keyframes`
}
`;
-interface SocialViewerUser {
- avatarUrl?: string | null;
- name: string;
-}
-
export type SocialViewerInitialScreen = "photo" | "likes";
export type SocialViewerPostActionMode =
@@ -84,78 +79,38 @@ const socialViewerPostActionConfigs: Record<
export interface SocialViewerPhoto {
alt?: string;
avatarUrl?: string | null;
+ caption?: string;
friendID?: string;
height?: number;
imageUrl: string;
+ likeCount?: number;
name: string;
+ postId?: number;
timestampMs: number;
+ viewerLiked?: boolean;
width?: number;
}
interface SocialFileViewerProps {
- currentUser?: SocialViewerUser;
initialScreen?: SocialViewerInitialScreen;
onClose: () => void;
- onDeletePost?: () => void;
+ onDeletePost?: () => Promise<void> | void;
+ onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;
onOpenFriend?: (friendID: string) => void;
onOpenProfile?: () => void;
+ onPublishDraftPost?: (caption: string) => Promise<void>;
+ onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
photo: SocialViewerPhoto;
postActionMode?: SocialViewerPostActionMode;
}
-interface SocialLiker {
+export interface SocialLiker {
id: string;
avatarUrl?: string | null;
friendID?: string;
name: string;
}
-const mockPhotoLikers: SocialLiker[] = [
- {
- id: "mira",
- avatarUrl: "/images/sample-feed-3.jpg",
- friendID: "mira-sen",
- name: "Mira Sen",
- },
- {
- id: "kabir",
- avatarUrl: "/images/sample-feed-1.jpg",
- friendID: "kabir-menon",
- name: "Kabir Menon",
- },
- {
- id: "devika",
- avatarUrl: "/images/sample-feed-2.jpg",
- friendID: "isha-mehta",
- name: "Isha Mehta",
- },
- {
- id: "nikhil",
- avatarUrl: "/images/sample-feed-5.jpg",
- friendID: "nikhil-rao",
- name: "Nikhil Rao",
- },
-];
-
-const friendIDForPersonName = (name: string): string | undefined => {
- switch (name.trim()) {
- case "Aparna Bhatnagar":
- return "aparna-bhatnagar";
- case "Isha Mehta":
- return "isha-mehta";
- case "Kabir Menon":
- return "kabir-menon";
- case "Riya Kapoor":
- return "riya-kapoor";
- case "Mira Sen":
- return "mira-sen";
- case "Nikhil Rao":
- return "nikhil-rao";
- default:
- return undefined;
- }
-};
-
const viewerActionButtonSx = {
alignItems: "center",
bgcolor: controlBackground,
@@ -270,13 +225,18 @@ const resizeCaptionInput = (input: HTMLTextAreaElement | null) => {
input.scrollHeight > captionInputMaxHeight ? "auto" : "hidden";
};
+const wait = (durationMs: number) =>
+ new Promise((resolve) => window.setTimeout(resolve, durationMs));
+
export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
- currentUser,
initialScreen = "photo",
onClose,
onDeletePost,
+ onLoadPostLikers,
onOpenFriend,
onOpenProfile,
+ onPublishDraftPost,
+ onSetPostLiked,
photo,
postActionMode = "like-with-count",
}) => {
@@ -293,8 +253,15 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
const [screen, setScreen] = React.useState<SocialViewerInitialScreen>(
resolvedInitialScreen,
);
- const [isPhotoLiked, setIsPhotoLiked] = React.useState(false);
- const [caption, setCaption] = React.useState("");
+ const [isPhotoLiked, setIsPhotoLiked] = React.useState(
+ photo.viewerLiked ?? false,
+ );
+ const [caption, setCaption] = React.useState(photo.caption ?? "");
+ const [serverLikeCount, setServerLikeCount] = React.useState(
+ photo.likeCount ?? 0,
+ );
+ const [photoLikers, setPhotoLikers] = React.useState<SocialLiker[]>([]);
+ const [isLoadingLikers, setIsLoadingLikers] = React.useState(false);
const [draftPostActionPhase, setDraftPostActionPhase] =
React.useState<SocialActionPhase | null>(null);
const displayName = firstNameFrom(photo.name);
@@ -309,19 +276,7 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
const ignoreNextLikeClickRef = React.useRef(false);
const suppressNextLikeContextMenuRef = React.useRef(false);
const suppressLikeContextMenuTimeoutRef = React.useRef<number | null>(null);
- const photoLikers = React.useMemo(() => {
- if (!isPhotoLiked) return mockPhotoLikers;
-
- return [
- {
- id: "current-user",
- avatarUrl: currentUser?.avatarUrl,
- name: "You",
- },
- ...mockPhotoLikers,
- ];
- }, [currentUser?.avatarUrl, isPhotoLiked]);
- const likeCount = photoLikers.length;
+ const likeCount = serverLikeCount;
const likeCountLabel = `${likeCount} ${likeCount == 1 ? "like" : "likes"}`;
const [actionsAnchor, setActionsAnchor] =
React.useState<HTMLElement | null>(null);
@@ -359,6 +314,15 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
clearLikeHoldTimeout();
setScreen("likes");
+ if (!photo.postId || !onLoadPostLikers) return;
+
+ setIsLoadingLikers(true);
+ void onLoadPostLikers(photo.postId)
+ .then(setPhotoLikers)
+ .catch((error: unknown) =>
+ console.error("Failed to load post likers", error),
+ )
+ .finally(() => setIsLoadingLikers(false));
};
const closeLikes = React.useCallback(() => {
@@ -376,7 +340,23 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
return;
}
- setIsPhotoLiked((isLiked) => !isLiked);
+ if (!photo.postId || !onSetPostLiked) {
+ setIsPhotoLiked((isLiked) => !isLiked);
+ return;
+ }
+
+ const nextLiked = !isPhotoLiked;
+ setIsPhotoLiked(nextLiked);
+ setServerLikeCount((count) =>
+ Math.max(0, count + (nextLiked ? 1 : -1)),
+ );
+ void onSetPostLiked(photo.postId, nextLiked).catch((error: unknown) => {
+ console.error("Failed to update post like", error);
+ setIsPhotoLiked(!nextLiked);
+ setServerLikeCount((count) =>
+ Math.max(0, count + (nextLiked ? -1 : 1)),
+ );
+ });
};
const handlePhotoLikeContextMenu = (
@@ -443,12 +423,42 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
const confirmDeletePost = () => {
if (isDeleteActionRunning || isDeleteExit) return;
setDeleteActionPhase("busy");
+ void (async () => {
+ try {
+ await Promise.all([
+ Promise.resolve(onDeletePost?.()),
+ wait(socialActionBusyDurationMs),
+ ]);
+ setDeleteActionPhase("done");
+ } catch (error) {
+ console.error("Failed to delete social post", error);
+ setDeleteActionPhase(null);
+ }
+ })();
};
const publishDraftPost = () => {
- if (!isDraftPost || isDraftPostActionRunning || isDeleteExit) return;
+ if (
+ !isDraftPost ||
+ isDraftPostActionRunning ||
+ isDeleteExit ||
+ !onPublishDraftPost
+ )
+ return;
setDraftPostActionPhase("busy");
+ void (async () => {
+ try {
+ await Promise.all([
+ onPublishDraftPost(caption),
+ wait(socialActionBusyDurationMs),
+ ]);
+ setDraftPostActionPhase("done");
+ } catch (error) {
+ console.error("Failed to publish social post", error);
+ setDraftPostActionPhase(null);
+ }
+ })();
};
const openFriendProfile = (friendID: string) => {
@@ -494,48 +504,42 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
}, []);
React.useEffect(() => {
- if (!deleteActionPhase) return;
-
- const timeoutID = window.setTimeout(
- () => {
- if (deleteActionPhase == "busy") {
- setDeleteActionPhase("done");
- return;
- }
-
- setDeleteSheetOpen(false);
- onDeletePost?.();
- setIsDeleteExit(true);
- },
- deleteActionPhase == "busy"
- ? socialActionBusyDurationMs
- : socialActionDoneDurationMs,
- );
+ if (deleteActionPhase != "done") return;
+
+ const timeoutID = window.setTimeout(() => {
+ setDeleteSheetOpen(false);
+ setIsDeleteExit(true);
+ }, socialActionDoneDurationMs);
return () => window.clearTimeout(timeoutID);
- }, [deleteActionPhase, onDeletePost]);
+ }, [deleteActionPhase]);
React.useEffect(() => {
- if (!draftPostActionPhase) return;
+ if (draftPostActionPhase != "done") return;
- const timeoutID = window.setTimeout(
- () => {
- if (draftPostActionPhase == "busy") {
- setDraftPostActionPhase("done");
- return;
- }
-
- setActivePostActionMode("like-with-count");
- setDraftPostActionPhase(null);
- },
- draftPostActionPhase == "busy"
- ? socialActionBusyDurationMs
- : socialActionDoneDurationMs,
- );
+ const timeoutID = window.setTimeout(() => {
+ setActivePostActionMode("like-with-count");
+ setDraftPostActionPhase(null);
+ }, socialActionDoneDurationMs);
return () => window.clearTimeout(timeoutID);
}, [draftPostActionPhase]);
+ React.useEffect(() => {
+ setIsPhotoLiked(photo.viewerLiked ?? false);
+ setCaption(photo.caption ?? "");
+ setServerLikeCount(photo.likeCount ?? 0);
+ setPhotoLikers([]);
+ setScreen(resolvedInitialScreen);
+ }, [
+ photo.caption,
+ photo.imageUrl,
+ photo.likeCount,
+ photo.postId,
+ photo.viewerLiked,
+ resolvedInitialScreen,
+ ]);
+
const handleDeleteSheetExited = () => {
if (!isDeleteExit) return;
@@ -1318,7 +1322,25 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
width: "100%",
}}
>
- {photoLikers.length == 0 ? (
+ {isLoadingLikers ? (
+ <Box
+ sx={{
+ alignItems: "center",
+ color: viewerPanelMuted,
+ display: "flex",
+ flex: "1 1 auto",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 600,
+ justifyContent: "center",
+ lineHeight: "20px",
+ minHeight: "100%",
+ }}
+ >
+ Loading likes...
+ </Box>
+ ) : photoLikers.length == 0 ? (
<Box
sx={{
alignItems: "center",
@@ -1339,9 +1361,7 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
) : (
photoLikers.map((liker) => {
const likerName = firstNameFrom(liker.name);
- const friendID =
- liker.friendID ??
- friendIDForPersonName(liker.name);
+ const friendID = liker.friendID;
const canOpenFriend = Boolean(
friendID && onOpenFriend,
);
diff --git a/web/apps/social/src/data/friends.ts b/web/apps/social/src/data/friends.ts
index 4dd1eb4638..84bca3e50b 100644
--- a/web/apps/social/src/data/friends.ts
+++ b/web/apps/social/src/data/friends.ts
@@ -1,59 +1,9 @@
export interface FriendProfile {
- avatarUrl: string;
+ avatarUrl?: string | null;
friendsCount: number;
fullName: string;
id: string;
username: string;
+ wallId?: string;
+ wallSlug?: string;
}
-
-export const sampleFriends: FriendProfile[] = [
- {
- avatarUrl: "/images/sample-feed-4.jpg",
- friendsCount: 12,
- fullName: "Aparna Bhatnagar",
- id: "aparna-bhatnagar",
- username: "aparnab",
- },
- {
- avatarUrl: "/images/sample-feed-3.jpg",
- friendsCount: 18,
- fullName: "Mira Sen",
- id: "mira-sen",
- username: "mirasen",
- },
- {
- avatarUrl: "/images/sample-feed-5.jpg",
- friendsCount: 9,
- fullName: "Nikhil Rao",
- id: "nikhil-rao",
- username: "nikhilrao",
- },
- {
- avatarUrl: "/images/sample-feed-6.jpg",
- friendsCount: 24,
- fullName: "Riya Kapoor",
- id: "riya-kapoor",
- username: "riyakapoor",
- },
- {
- avatarUrl: "/images/sample-feed-1.jpg",
- friendsCount: 15,
- fullName: "Dev Shah",
- id: "dev-shah",
- username: "devshah",
- },
- {
- avatarUrl: "/images/sample-feed-2.jpg",
- friendsCount: 7,
- fullName: "Isha Mehta",
- id: "isha-mehta",
- username: "ishamehta",
- },
- {
- avatarUrl: "/images/sample-avatar.jpg",
- friendsCount: 21,
- fullName: "Kabir Menon",
- id: "kabir-menon",
- username: "kabirmenon",
- },
-];
diff --git a/web/apps/social/src/pages/app/friend.tsx b/web/apps/social/src/pages/app/friend.tsx
index c618b0b6b8..4a8f780571 100644
--- a/web/apps/social/src/pages/app/friend.tsx
+++ b/web/apps/social/src/pages/app/friend.tsx
@@ -1,16 +1,23 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
-import { sampleFriends } from "data/friends";
import { useRouter } from "next/router";
-import React, { useEffect } from "react";
+import React, { useEffect, useMemo, useState } from "react";
import { friendsBackground } from "screens/FriendsScreen";
import { ProfileScreen } from "screens/ProfileScreen";
+import {
+ loadCurrentPostLikers,
+ loadCurrentWallFriends,
+ loadCurrentWallPostsPage,
+ setCurrentPostLiked,
+ type SocialWallPost,
+} from "services/socialWall";
import { useSocialAppState } from "state/socialAppState";
import {
friendIDFromQuery,
friendProfileSourceFromQuery,
socialRoutes,
} from "utils/socialRoutes";
+import { profilePostGroupsFromPosts } from "utils/socialWallDisplay";
const backRouteForSource = (
source: ReturnType<typeof friendProfileSourceFromQuery>,
@@ -25,12 +32,14 @@ const backRouteForSource = (
const Page: React.FC = () => {
const router = useRouter();
- const { friends, profile, profileLoadStatus } = useSocialAppState();
+ const { friends, profile, profileLoadStatus, setFriends } =
+ useSocialAppState();
const friendID = friendIDFromQuery(router.query.friendID);
const backSource = friendProfileSourceFromQuery(router.query.from);
- const selectedFriend =
- friends.find((friend) => friend.id == friendID) ??
- sampleFriends.find((friend) => friend.id == friendID);
+ const selectedFriend = friends.find((friend) => friend.id == friendID);
+ const [friendsLoadAttempted, setFriendsLoadAttempted] = useState(false);
+ const [posts, setPosts] = useState<SocialWallPost[]>([]);
+ const postGroups = useMemo(() => profilePostGroupsFromPosts(posts), [posts]);
useEffect(() => {
if (!router.isReady) return;
@@ -38,8 +47,41 @@ const Page: React.FC = () => {
void router.replace(socialRoutes.onboarding);
return;
}
- if (!selectedFriend) void router.replace(socialRoutes.friends);
- }, [profile, profileLoadStatus, router, selectedFriend]);
+ if (
+ profileLoadStatus == "ready" &&
+ friendsLoadAttempted &&
+ !selectedFriend
+ ) {
+ void router.replace(socialRoutes.friends);
+ }
+ }, [
+ friendsLoadAttempted,
+ profile,
+ profileLoadStatus,
+ router,
+ selectedFriend,
+ ]);
+
+ useEffect(() => {
+ if (!profile?.wallId) return;
+
+ void loadCurrentWallFriends(profile.wallId)
+ .then(setFriends)
+ .catch((error: unknown) =>
+ console.error("Failed to load social friends", error),
+ )
+ .finally(() => setFriendsLoadAttempted(true));
+ }, [profile?.wallId, setFriends]);
+
+ useEffect(() => {
+ if (!selectedFriend?.wallId) return;
+
+ void loadCurrentWallPostsPage(selectedFriend.wallId)
+ .then((page) => setPosts(page.items))
+ .catch((error: unknown) =>
+ console.error("Failed to load friend posts", error),
+ );
+ }, [selectedFriend?.wallId]);
if (
!router.isReady ||
@@ -56,10 +98,13 @@ const Page: React.FC = () => {
<ProfileScreen
friendsCount={selectedFriend.friendsCount}
headerVariant="friend"
+ postGroups={postGroups}
profile={{
- avatarUrl: selectedFriend.avatarUrl,
+ avatarUrl: selectedFriend.avatarUrl ?? null,
fullName: selectedFriend.fullName,
username: selectedFriend.username,
+ wallId: selectedFriend.wallId,
+ wallSlug: selectedFriend.wallSlug,
}}
onBack={() => void router.push(backRouteForSource(backSource))}
onOpenFriend={(nextFriendID) =>
@@ -67,6 +112,8 @@ const Page: React.FC = () => {
socialRoutes.friend(nextFriendID, backSource),
)
}
+ onLoadPostLikers={loadCurrentPostLikers}
+ onSetPostLiked={setCurrentPostLiked}
/>
</>
);
diff --git a/web/apps/social/src/pages/app/friends.tsx b/web/apps/social/src/pages/app/friends.tsx
index 920df9de9e..6f6fd7d6ff 100644
--- a/web/apps/social/src/pages/app/friends.tsx
+++ b/web/apps/social/src/pages/app/friends.tsx
@@ -3,6 +3,10 @@ import { SocialRouteFallback } from "components/SocialRouteFallback";
import { useRouter } from "next/router";
import React, { useEffect } from "react";
import { FriendsScreen, friendsBackground } from "screens/FriendsScreen";
+import {
+ loadCurrentWallFriends,
+ removeCurrentWallFriend,
+} from "services/socialWall";
import { useSocialAppState } from "state/socialAppState";
import { socialRoutes } from "utils/socialRoutes";
@@ -17,6 +21,16 @@ const Page: React.FC = () => {
}
}, [profile, profileLoadStatus, router]);
+ useEffect(() => {
+ if (!profile?.wallId) return;
+
+ void loadCurrentWallFriends(profile.wallId)
+ .then(setFriends)
+ .catch((error: unknown) =>
+ console.error("Failed to load social friends", error),
+ );
+ }, [profile?.wallId, setFriends]);
+
if (profileLoadStatus == "loading" || !profile) {
return <SocialRouteFallback background={friendsBackground} />;
}
@@ -30,13 +44,17 @@ const Page: React.FC = () => {
onOpenFriend={(friendID) =>
void router.push(socialRoutes.friend(friendID, "friends"))
}
- onUnfriend={(friendID) =>
+ onUnfriend={(friendID) => {
+ const friend = friends.find(
+ (candidate) => candidate.id == friendID,
+ );
+ if (friend?.wallId) void removeCurrentWallFriend(friend.wallId);
setFriends((currentFriends) =>
currentFriends.filter(
- (friend) => friend.id != friendID,
+ (candidate) => candidate.id != friendID,
),
- )
- }
+ );
+ }}
/>
</>
);
diff --git a/web/apps/social/src/pages/app/index.tsx b/web/apps/social/src/pages/app/index.tsx
index 4e0d082f39..779894447b 100644
--- a/web/apps/social/src/pages/app/index.tsx
+++ b/web/apps/social/src/pages/app/index.tsx
@@ -1,14 +1,27 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
import { useRouter } from "next/router";
-import React, { useEffect } from "react";
+import React, { useEffect, useState } from "react";
import { HomeScreen, homeBackground } from "screens/HomeScreen";
+import {
+ createCurrentPhotoPost,
+ createCurrentProfileLink,
+ loadCurrentFeedPage,
+ loadCurrentPostLikers,
+ loadCurrentWallFriends,
+ setCurrentPostLiked,
+ type SocialWallPost,
+} from "services/socialWall";
import { useSocialAppState } from "state/socialAppState";
import { socialRoutes } from "utils/socialRoutes";
+import { socialPostToViewerPhoto } from "utils/socialWallDisplay";
const Page: React.FC = () => {
const router = useRouter();
- const { friends, profile, profileLoadStatus } = useSocialAppState();
+ const { friends, profile, profileLoadStatus, setFriends } =
+ useSocialAppState();
+ const [feedItems, setFeedItems] = useState<SocialWallPost[]>([]);
+ const [isFeedLoading, setIsFeedLoading] = useState(false);
useEffect(() => {
if (profileLoadStatus == "ready" && !profile) {
@@ -16,6 +29,32 @@ const Page: React.FC = () => {
}
}, [profile, profileLoadStatus, router]);
+ useEffect(() => {
+ if (!profile?.wallId) return;
+
+ let cancelled = false;
+ setIsFeedLoading(true);
+ void Promise.all([
+ loadCurrentFeedPage(),
+ loadCurrentWallFriends(profile.wallId),
+ ])
+ .then(([feed, nextFriends]) => {
+ if (cancelled) return;
+ setFeedItems(feed.items);
+ setFriends(nextFriends);
+ })
+ .catch((error: unknown) =>
+ console.error("Failed to load social home", error),
+ )
+ .finally(() => {
+ if (!cancelled) setIsFeedLoading(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [profile?.wallId, setFriends]);
+
if (profileLoadStatus == "loading" || !profile) {
return <SocialRouteFallback background={homeBackground} />;
}
@@ -24,8 +63,21 @@ const Page: React.FC = () => {
<>
<SocialPageMeta themeColor={homeBackground} />
<HomeScreen
+ feedItems={feedItems}
friendsCount={friends.length}
+ isFeedLoading={isFeedLoading}
profile={profile}
+ onCreatePost={async (file, caption) => {
+ if (!profile.wallId) throw new Error("Missing wall.");
+ const post = await createCurrentPhotoPost({
+ caption,
+ file,
+ wallId: profile.wallId,
+ });
+ if (!post) throw new Error("Couldn't create post.");
+ setFeedItems((currentItems) => [post, ...currentItems]);
+ return socialPostToViewerPhoto(post);
+ }}
onOpenFriend={(friendID) =>
void router.push(socialRoutes.friend(friendID, "home"))
}
@@ -33,6 +85,12 @@ const Page: React.FC = () => {
void router.push(socialRoutes.notifications)
}
onOpenProfile={() => void router.push(socialRoutes.profile)}
+ onLoadPostLikers={loadCurrentPostLikers}
+ onSetPostLiked={setCurrentPostLiked}
+ onShareProfileLink={async () => {
+ if (!profile.wallId) throw new Error("Missing wall.");
+ return (await createCurrentProfileLink(profile.wallId)).url;
+ }}
/>
</>
);
diff --git a/web/apps/social/src/pages/app/notifications.tsx b/web/apps/social/src/pages/app/notifications.tsx
index 6def4ea9f9..944424dc64 100644
--- a/web/apps/social/src/pages/app/notifications.tsx
+++ b/web/apps/social/src/pages/app/notifications.tsx
@@ -1,17 +1,31 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
import { useRouter } from "next/router";
-import React, { useEffect } from "react";
+import React, { useEffect, useMemo, useState } from "react";
import {
NotificationsScreen,
notificationsBackground,
} from "screens/NotificationsScreen";
+import {
+ loadCurrentNotificationsPage,
+ loadCurrentPostLikers,
+ setCurrentPostLiked,
+ type SocialWallNotification,
+} from "services/socialWall";
import { useSocialAppState } from "state/socialAppState";
import { socialRoutes } from "utils/socialRoutes";
+import { notificationForScreen } from "utils/socialWallDisplay";
const Page: React.FC = () => {
const router = useRouter();
const { profile, profileLoadStatus } = useSocialAppState();
+ const [notifications, setNotifications] = useState<
+ SocialWallNotification[]
+ >([]);
+ const screenNotifications = useMemo(
+ () => notifications.map(notificationForScreen),
+ [notifications],
+ );
useEffect(() => {
if (profileLoadStatus == "ready" && !profile) {
@@ -19,6 +33,16 @@ const Page: React.FC = () => {
}
}, [profile, profileLoadStatus, router]);
+ useEffect(() => {
+ if (!profile) return;
+
+ void loadCurrentNotificationsPage()
+ .then((page) => setNotifications(page.items))
+ .catch((error: unknown) =>
+ console.error("Failed to load notifications", error),
+ );
+ }, [profile]);
+
if (profileLoadStatus == "loading" || !profile) {
return <SocialRouteFallback background={notificationsBackground} />;
}
@@ -27,12 +51,15 @@ const Page: React.FC = () => {
<>
<SocialPageMeta themeColor={notificationsBackground} />
<NotificationsScreen
+ notifications={screenNotifications}
onBack={() => void router.push(socialRoutes.home)}
onOpenFriend={(friendID) =>
void router.push(
socialRoutes.friend(friendID, "notifications"),
)
}
+ onLoadPostLikers={loadCurrentPostLikers}
+ onSetPostLiked={setCurrentPostLiked}
profile={profile}
/>
</>
diff --git a/web/apps/social/src/pages/app/profile.tsx b/web/apps/social/src/pages/app/profile.tsx
index 53dc6e83c3..f031f66f9a 100644
--- a/web/apps/social/src/pages/app/profile.tsx
+++ b/web/apps/social/src/pages/app/profile.tsx
@@ -1,14 +1,32 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
import { useRouter } from "next/router";
-import React, { useEffect } from "react";
+import React, { useEffect, useMemo, useState } from "react";
import { ProfileScreen, profileBackground } from "screens/ProfileScreen";
+import {
+ createCurrentPhotoPost,
+ createCurrentProfileLink,
+ deleteCurrentPost,
+ loadCurrentPostLikers,
+ loadCurrentWallFriends,
+ loadCurrentWallPostsPage,
+ setCurrentPostLiked,
+ type SocialWallPost,
+} from "services/socialWall";
import { useSocialAppState } from "state/socialAppState";
import { socialRoutes } from "utils/socialRoutes";
+import {
+ profilePostGroupsFromPosts,
+ socialPostToViewerPhoto,
+} from "utils/socialWallDisplay";
const Page: React.FC = () => {
const router = useRouter();
- const { friends, profile, profileLoadStatus } = useSocialAppState();
+ const { friends, profile, profileLoadStatus, setFriends } =
+ useSocialAppState();
+ const [posts, setPosts] = useState<SocialWallPost[]>([]);
+ const [isPostsLoading, setIsPostsLoading] = useState(false);
+ const postGroups = useMemo(() => profilePostGroupsFromPosts(posts), [posts]);
useEffect(() => {
if (profileLoadStatus == "ready" && !profile) {
@@ -16,6 +34,32 @@ const Page: React.FC = () => {
}
}, [profile, profileLoadStatus, router]);
+ useEffect(() => {
+ if (!profile?.wallId) return;
+
+ let cancelled = false;
+ setIsPostsLoading(true);
+ void Promise.all([
+ loadCurrentWallPostsPage(profile.wallId),
+ loadCurrentWallFriends(profile.wallId),
+ ])
+ .then(([page, nextFriends]) => {
+ if (cancelled) return;
+ setPosts(page.items);
+ setFriends(nextFriends);
+ })
+ .catch((error: unknown) =>
+ console.error("Failed to load social profile", error),
+ )
+ .finally(() => {
+ if (!cancelled) setIsPostsLoading(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [profile?.wallId, setFriends]);
+
if (profileLoadStatus == "loading" || !profile) {
return <SocialRouteFallback background={profileBackground} />;
}
@@ -25,13 +69,38 @@ const Page: React.FC = () => {
<SocialPageMeta themeColor={profileBackground} />
<ProfileScreen
friendsCount={friends.length}
+ isPostsLoading={isPostsLoading}
+ postGroups={postGroups}
profile={profile}
onBack={() => void router.push(socialRoutes.home)}
+ onCreatePost={async (file, caption) => {
+ if (!profile.wallId) throw new Error("Missing wall.");
+ const post = await createCurrentPhotoPost({
+ caption,
+ file,
+ wallId: profile.wallId,
+ });
+ if (!post) throw new Error("Couldn't create post.");
+ setPosts((currentPosts) => [post, ...currentPosts]);
+ return socialPostToViewerPhoto(post);
+ }}
+ onDeletePost={async (postId) => {
+ await deleteCurrentPost(postId);
+ setPosts((currentPosts) =>
+ currentPosts.filter((post) => post.postId != postId),
+ );
+ }}
onOpenFriend={(friendID) =>
void router.push(socialRoutes.friend(friendID, "profile"))
}
onOpenFriends={() => void router.push(socialRoutes.friends)}
onOpenSettings={() => void router.push(socialRoutes.settings)}
+ onLoadPostLikers={loadCurrentPostLikers}
+ onSetPostLiked={setCurrentPostLiked}
+ onShareProfileLink={async () => {
+ if (!profile.wallId) throw new Error("Missing wall.");
+ return (await createCurrentProfileLink(profile.wallId)).url;
+ }}
/>
</>
);
diff --git a/web/apps/social/src/pages/index.tsx b/web/apps/social/src/pages/index.tsx
index 052110ecd1..22564d655b 100644
--- a/web/apps/social/src/pages/index.tsx
+++ b/web/apps/social/src/pages/index.tsx
@@ -1,7 +1,7 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
import { useRouter } from "next/router";
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useMemo, useState } from "react";
import {
OnboardingScreen,
addFriendOnboardingDescription,
@@ -11,6 +11,17 @@ import {
import { profileBackground } from "screens/ProfileScreen";
import { PublicProfileScreen } from "screens/PublicProfileScreen";
import type { SetupProfile } from "screens/SetupProfileScreen";
+import {
+ clearPendingSocialInvite,
+ savePendingSocialInvite,
+ socialInviteFromLocation,
+ type PendingSocialInvite,
+} from "services/socialInvite";
+import {
+ joinSocialInvite,
+ loadPublicSocialInvite,
+ type SocialWallPost,
+} from "services/socialWall";
import {
type OnboardingEntrySource,
useSocialAppState,
@@ -20,35 +31,12 @@ import {
onboardingSourceSearchParam,
socialRoutes,
} from "utils/socialRoutes";
-
-const samplePublicProfileData = {
- avatarUrl: "/images/sample-avatar.jpg",
- fullName: "Anand Baburajan",
- username: "anandbaburajan",
-};
-
-interface PublicProfileLink {
- token: string;
- username: string;
-}
+import { profilePostGroupsFromPosts } from "utils/socialWallDisplay";
type RouteMode =
| { kind: "checking" }
| { kind: "app" }
- | ({ kind: "public-profile" } & PublicProfileLink);
-
-const parsePublicProfileLink = (): PublicProfileLink | null => {
- const match = /^\/([^/]+)\/?$/.exec(window.location.pathname);
- const token = window.location.hash.slice(1);
- if (!match || !token) return null;
-
- try {
- const username = decodeURIComponent(match[1] ?? "").trim();
- return username ? { token, username } : null;
- } catch {
- return null;
- }
-};
+ | ({ kind: "public-profile" } & PendingSocialInvite);
const parseOnboardingEntrySource = (): OnboardingEntrySource => {
const params = new URLSearchParams(window.location.search);
@@ -70,12 +58,6 @@ const removeOnboardingEntrySourceFromURL = () => {
);
};
-const publicProfileFromLink = (): SetupProfile => ({
- avatarUrl: samplePublicProfileData.avatarUrl,
- fullName: samplePublicProfileData.fullName,
- username: samplePublicProfileData.username,
-});
-
const Page: React.FC = () => {
const router = useRouter();
const {
@@ -85,20 +67,58 @@ const Page: React.FC = () => {
setOnboardingEntrySource,
} = useSocialAppState();
const [routeMode, setRouteMode] = useState<RouteMode>({ kind: "checking" });
+ const [publicProfile, setPublicProfile] = useState<SetupProfile | null>(
+ null,
+ );
+ const [publicFriendsCount, setPublicFriendsCount] = useState(0);
+ const [publicPosts, setPublicPosts] = useState<SocialWallPost[]>([]);
+ const [publicError, setPublicError] = useState<string>();
+ const publicPostGroups = useMemo(
+ () => profilePostGroupsFromPosts(publicPosts),
+ [publicPosts],
+ );
useEffect(() => {
- const publicProfileLink = parsePublicProfileLink();
- if (!publicProfileLink) {
+ const publicInvite = socialInviteFromLocation();
+ if (!publicInvite) {
setOnboardingEntrySource(parseOnboardingEntrySource());
removeOnboardingEntrySourceFromURL();
}
setRouteMode(
- publicProfileLink
- ? { kind: "public-profile", ...publicProfileLink }
+ publicInvite
+ ? { kind: "public-profile", ...publicInvite }
: { kind: "app" },
);
}, [setOnboardingEntrySource]);
+ useEffect(() => {
+ if (routeMode.kind != "public-profile") return;
+
+ let cancelled = false;
+ setPublicError(undefined);
+ void loadPublicSocialInvite(routeMode)
+ .then(({ posts, profile: nextProfile }) => {
+ if (cancelled) return;
+ setPublicProfile({
+ avatarUrl: nextProfile.avatarUrl ?? null,
+ fullName: nextProfile.fullName,
+ username: nextProfile.username,
+ wallId: nextProfile.wallId,
+ wallSlug: nextProfile.wallSlug,
+ });
+ setPublicFriendsCount(nextProfile.friendsCount);
+ setPublicPosts(posts);
+ })
+ .catch((error: unknown) => {
+ console.error("Failed to load public social invite", error);
+ if (!cancelled) setPublicError("This invite link is invalid or expired.");
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [routeMode]);
+
useEffect(() => {
if (
routeMode.kind == "app" &&
@@ -118,13 +138,48 @@ const Page: React.FC = () => {
}
if (routeMode.kind == "public-profile") {
+ if (!publicProfile && !publicError) {
+ return <SocialRouteFallback background={profileBackground} />;
+ }
+
+ if (!publicProfile) {
+ return (
+ <>
+ <SocialPageMeta themeColor={profileBackground} />
+ <OnboardingScreen
+ description={publicError}
+ onCreateAccount={() => void router.push(socialRoutes.signup)}
+ onLogin={() => void router.push(socialRoutes.login)}
+ title="Invite unavailable"
+ />
+ </>
+ );
+ }
+
return (
<>
<SocialPageMeta themeColor={profileBackground} />
<PublicProfileScreen
- profile={publicProfileFromLink()}
+ friendsCount={publicFriendsCount}
+ postGroups={publicPostGroups}
+ profile={publicProfile}
onAddFriend={() => {
+ savePendingSocialInvite(routeMode);
setOnboardingEntrySource("add-friend-link");
+ if (profile) {
+ void joinSocialInvite(routeMode)
+ .then(() => {
+ clearPendingSocialInvite();
+ void router.push(socialRoutes.home);
+ })
+ .catch((error: unknown) =>
+ console.error(
+ "Failed to join social invite",
+ error,
+ ),
+ );
+ return;
+ }
window.location.assign(
`/?${onboardingSourceSearchParam}=${addFriendLinkOnboardingSource}`,
);
diff --git a/web/apps/social/src/pages/invite.tsx b/web/apps/social/src/pages/invite.tsx
index b8fe338bca..4ef87c5d6e 100644
--- a/web/apps/social/src/pages/invite.tsx
+++ b/web/apps/social/src/pages/invite.tsx
@@ -1,17 +1,21 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
import { useRouter } from "next/router";
-import React, { useEffect } from "react";
+import React, { useCallback, useEffect, useState } from "react";
import {
ShareProfileLinkScreen,
shareProfileLinkBackground,
} from "screens/ShareProfileLinkScreen";
+import { createCurrentProfileLink } from "services/socialWall";
import { useSocialAppState } from "state/socialAppState";
import { socialRoutes } from "utils/socialRoutes";
const Page: React.FC = () => {
const router = useRouter();
const { profile, profileLoadStatus } = useSocialAppState();
+ const [profileLink, setProfileLink] = useState<string>();
+ const [linkError, setLinkError] = useState<string>();
+ const [isLinkLoading, setIsLinkLoading] = useState(false);
useEffect(() => {
if (profileLoadStatus == "ready" && !profile) {
@@ -19,6 +23,25 @@ const Page: React.FC = () => {
}
}, [profile, profileLoadStatus, router]);
+ const loadInviteLink = useCallback(async () => {
+ if (!profile?.wallId) return;
+
+ setIsLinkLoading(true);
+ setLinkError(undefined);
+ try {
+ setProfileLink((await createCurrentProfileLink(profile.wallId)).url);
+ } catch (error) {
+ console.error("Failed to create social invite link", error);
+ setLinkError("Couldn't create invite link. Tap to retry.");
+ } finally {
+ setIsLinkLoading(false);
+ }
+ }, [profile?.wallId]);
+
+ useEffect(() => {
+ if (!profileLink) void loadInviteLink();
+ }, [loadInviteLink, profileLink]);
+
if (profileLoadStatus == "loading" || !profile) {
return <SocialRouteFallback background={shareProfileLinkBackground} />;
}
@@ -27,11 +50,15 @@ const Page: React.FC = () => {
<>
<SocialPageMeta themeColor={shareProfileLinkBackground} />
<ShareProfileLinkScreen
+ errorMessage={linkError}
+ isLinkLoading={isLinkLoading}
profile={profile}
onBack={() =>
void router.push(socialRoutes.setupProfile("verify"))
}
onDone={() => void router.push(socialRoutes.home)}
+ onRetry={() => void loadInviteLink()}
+ profileLink={profileLink}
/>
</>
);
diff --git a/web/apps/social/src/pages/setup-profile.tsx b/web/apps/social/src/pages/setup-profile.tsx
index 743ca07c7a..eb7de30702 100644
--- a/web/apps/social/src/pages/setup-profile.tsx
+++ b/web/apps/social/src/pages/setup-profile.tsx
@@ -1,17 +1,22 @@
import { SocialPageMeta } from "components/SocialPageMeta";
import { SocialRouteFallback } from "components/SocialRouteFallback";
import { useRouter } from "next/router";
-import React, { useEffect, useMemo, useState } from "react";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
SetupProfileScreen,
setupProfileBackground,
} from "screens/SetupProfileScreen";
+import {
+ clearPendingSocialInvite,
+ savedPendingSocialInvite,
+} from "services/socialInvite";
import {
saveSocialProfile,
socialProfileErrorMessage,
socialUsernameAvailability,
socialUsernameValidationError,
} from "services/socialProfile";
+import { joinSocialInvite } from "services/socialWall";
import { useSocialAppState } from "state/socialAppState";
import { setupProfileSourceFromQuery, socialRoutes } from "utils/socialRoutes";
@@ -41,15 +46,33 @@ const Page: React.FC = () => {
[backSource, isAddFriendLinkOnboarding],
);
+ const acceptPendingInvite = useCallback(async () => {
+ const pendingInvite = savedPendingSocialInvite();
+ if (!pendingInvite) return;
+
+ await joinSocialInvite(pendingInvite);
+ clearPendingSocialInvite();
+ }, []);
+
useEffect(() => {
if (router.isReady) void refreshProfile();
}, [refreshProfile, router.isReady]);
useEffect(() => {
if (profileLoadStatus == "ready" && profile) {
- void router.replace(existingProfileRoute);
+ void acceptPendingInvite()
+ .catch((error: unknown) =>
+ console.error("Failed to accept pending invite", error),
+ )
+ .finally(() => void router.replace(existingProfileRoute));
}
- }, [existingProfileRoute, profile, profileLoadStatus, router]);
+ }, [
+ acceptPendingInvite,
+ existingProfileRoute,
+ profile,
+ profileLoadStatus,
+ router,
+ ]);
useEffect(() => {
if (profileLoadStatus != "ready" || profile) return;
@@ -115,6 +138,7 @@ const Page: React.FC = () => {
try {
const savedProfile =
await saveSocialProfile(nextProfile);
+ await acceptPendingInvite();
setProfile(savedProfile);
void router.push(
isAddFriendLinkOnboarding
diff --git a/web/apps/social/src/screens/HomeScreen.tsx b/web/apps/social/src/screens/HomeScreen.tsx
index 946f2a1f9d..f7ff02f1c3 100644
--- a/web/apps/social/src/screens/HomeScreen.tsx
+++ b/web/apps/social/src/screens/HomeScreen.tsx
@@ -7,6 +7,7 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Box } from "@mui/material";
import {
SocialFileViewer,
+ type SocialLiker,
type SocialViewerInitialScreen,
type SocialViewerPhoto,
type SocialViewerPostActionMode,
@@ -15,11 +16,11 @@ import { EnteLogo } from "ente-base/components/EnteLogo";
import React, { useState } from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
import { ShareIcon } from "screens/ShareProfileLinkScreen";
+import type { SocialWallPost } from "services/socialWall";
import {
createLocalPostPhoto,
type LocalPostPhotoDimensions,
} from "utils/localPostPhoto";
-import { profileLinkForUsername } from "utils/profileLink";
import {
firstNameFrom,
formatSocialDate,
@@ -43,139 +44,17 @@ const headerSideWidth = headerActionSize * 2 + headerActionGap;
const feedLikeActionInset = 4;
const feedLikeActionSize = 40;
-const minutesAgo = (minutes: number) => Date.now() - minutes * 60 * 1000;
-const hoursAgo = (hours: number) => minutesAgo(hours * 60);
-const daysAgo = (days: number) => hoursAgo(days * 24);
-const sampleFeedLandscapePhotoAspectRatio = 900 / 680;
-const sampleFeedPortraitPhotoAspectRatio = 680 / 1020;
-const showMockFeedData =
- process.env.NEXT_PUBLIC_HIDE_SOCIAL_MOCK_FEED != "true";
-
-const sampleFeedItems = [
- {
- aspectRatio: sampleFeedLandscapePhotoAspectRatio,
- avatarUrl: "/images/sample-feed-4.jpg",
- friendID: "aparna-bhatnagar",
- imageUrl: "/images/sample-feed-1.jpg",
- likeCount: 18,
- name: "Aparna Bhatnagar",
- timestampMs: minutesAgo(22),
- },
- {
- aspectRatio: sampleFeedPortraitPhotoAspectRatio,
- avatarUrl: "/images/sample-feed-3.jpg",
- friendID: "mira-sen",
- imageUrl: "/images/sample-feed-portrait-2.jpg",
- likeCount: 24,
- name: "Mira Sen",
- timestampMs: hoursAgo(2),
- },
- {
- aspectRatio: sampleFeedLandscapePhotoAspectRatio,
- avatarUrl: "/images/sample-feed-3.jpg",
- friendID: "mira-sen",
- imageUrl: "/images/sample-feed-2.jpg",
- likeCount: 15,
- name: "Mira Sen",
- timestampMs: hoursAgo(3),
- },
- {
- aspectRatio: sampleFeedPortraitPhotoAspectRatio,
- avatarUrl: "/images/sample-feed-5.jpg",
- friendID: "nikhil-rao",
- imageUrl: "/images/sample-feed-portrait-3.jpg",
- likeCount: 31,
- name: "Nikhil Rao",
- timestampMs: hoursAgo(7),
- },
- {
- aspectRatio: sampleFeedLandscapePhotoAspectRatio,
- avatarUrl: "/images/sample-feed-5.jpg",
- friendID: "nikhil-rao",
- imageUrl: "/images/sample-feed-3.jpg",
- likeCount: 11,
- name: "Nikhil Rao",
- timestampMs: daysAgo(1),
- },
- {
- aspectRatio: sampleFeedPortraitPhotoAspectRatio,
- avatarUrl: "/images/sample-feed-6.jpg",
- friendID: "riya-kapoor",
- imageUrl: "/images/sample-feed-portrait-4.jpg",
- likeCount: 28,
- name: "Riya Kapoor",
- timestampMs: daysAgo(1) - 3 * 60 * 60 * 1000,
- },
- {
- aspectRatio: sampleFeedLandscapePhotoAspectRatio,
- avatarUrl: "/images/sample-feed-6.jpg",
- friendID: "riya-kapoor",
- imageUrl: "/images/sample-feed-4.jpg",
- likeCount: 16,
- name: "Riya Kapoor",
- timestampMs: daysAgo(2),
- },
- {
- aspectRatio: sampleFeedPortraitPhotoAspectRatio,
- avatarUrl: "/images/sample-feed-4.jpg",
- friendID: "aparna-bhatnagar",
- imageUrl: "/images/sample-feed-portrait-1.jpg",
- likeCount: 22,
- name: "Aparna Bhatnagar",
- timestampMs: daysAgo(3),
- },
- {
- aspectRatio: sampleFeedLandscapePhotoAspectRatio,
- avatarUrl: "/images/sample-feed-4.jpg",
- friendID: "aparna-bhatnagar",
- imageUrl: "/images/sample-feed-5.jpg",
- likeCount: 13,
- name: "Aparna Bhatnagar",
- timestampMs: daysAgo(4),
- },
- {
- aspectRatio: sampleFeedPortraitPhotoAspectRatio,
- avatarUrl: "/images/sample-feed-3.jpg",
- friendID: "mira-sen",
- imageUrl: "/images/sample-feed-portrait-5.jpg",
- likeCount: 36,
- name: "Mira Sen",
- timestampMs: daysAgo(6),
- },
- {
- aspectRatio: sampleFeedLandscapePhotoAspectRatio,
- avatarUrl: "/images/sample-feed-3.jpg",
- friendID: "mira-sen",
- imageUrl: "/images/sample-feed-6.jpg",
- likeCount: 19,
- name: "Mira Sen",
- timestampMs: daysAgo(8),
- },
- {
- aspectRatio: sampleFeedPortraitPhotoAspectRatio,
- avatarUrl: "/images/sample-feed-5.jpg",
- friendID: "nikhil-rao",
- imageUrl: "/images/sample-feed-portrait-6.jpg",
- likeCount: 27,
- name: "Nikhil Rao",
- timestampMs: daysAgo(12),
- },
- {
- aspectRatio: sampleFeedLandscapePhotoAspectRatio,
- avatarUrl: "/images/sample-feed-5.jpg",
- friendID: "nikhil-rao",
- imageUrl: "/images/sample-feed-2.jpg",
- likeCount: 43,
- name: "Nikhil Rao",
- timestampMs: new Date(new Date().getFullYear() - 1, 10, 18).getTime(),
- },
-];
-
interface HomeScreenProps {
+ feedItems: SocialWallPost[];
friendsCount: number;
+ isFeedLoading?: boolean;
+ onCreatePost?: (file: File, caption: string) => Promise<SocialViewerPhoto>;
onOpenFriend?: (friendID: string) => void;
onOpenNotifications?: () => void;
onOpenProfile?: () => void;
+ onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;
+ onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
+ onShareProfileLink?: () => Promise<string>;
profile: SetupProfile;
}
@@ -185,6 +64,7 @@ interface FeedPhotoDimensions {
}
interface SelectedHomeViewer {
+ draftFile?: File;
initialScreen: SocialViewerInitialScreen;
localObjectUrl?: string;
photo: SocialViewerPhoto;
@@ -193,16 +73,20 @@ interface SelectedHomeViewer {
interface FeedItemProps {
aspectRatio: number;
- avatarUrl: string;
+ avatarUrl?: string | null;
friendID: string;
imageUrl: string;
+ likeCount: number;
name: string;
onOpenFriend?: (friendID: string) => void;
onOpenPhoto?: (
photo: SocialViewerPhoto,
initialScreen?: SocialViewerInitialScreen,
) => void;
+ onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
+ postId: number;
timestampMs: number;
+ viewerLiked: boolean;
}
const dimensionsFromAspectRatio = (
@@ -220,12 +104,17 @@ const FeedItem: React.FC<FeedItemProps> = ({
avatarUrl,
friendID,
imageUrl,
+ likeCount,
name,
onOpenFriend,
onOpenPhoto,
+ onSetPostLiked,
+ postId,
timestampMs,
+ viewerLiked,
}) => {
- const [isLiked, setIsLiked] = useState(false);
+ const [isLiked, setIsLiked] = useState(viewerLiked);
+ const [localLikeCount, setLocalLikeCount] = useState(likeCount);
const [isLikeButtonPopping, setIsLikeButtonPopping] = useState(false);
const firstName = firstNameFrom(name);
const dateLabel = formatSocialDate(timestampMs);
@@ -260,8 +149,11 @@ const FeedItem: React.FC<FeedItemProps> = ({
friendID,
height: photoDimensions.height,
imageUrl,
+ likeCount: localLikeCount,
name,
+ postId,
timestampMs,
+ viewerLiked: isLiked,
width: photoDimensions.width,
},
initialScreen,
@@ -271,13 +163,32 @@ const FeedItem: React.FC<FeedItemProps> = ({
window.clearTimeout(likePopTimeoutRef.current);
setIsLikeButtonPopping(true);
- setIsLiked((current) => !current);
+ const nextLiked = !isLiked;
+ setIsLiked(nextLiked);
+ setLocalLikeCount((count) =>
+ Math.max(0, count + (nextLiked ? 1 : -1)),
+ );
+ void onSetPostLiked?.(postId, nextLiked).catch((error: unknown) => {
+ console.error("Failed to update post like", error);
+ setIsLiked(!nextLiked);
+ setLocalLikeCount((count) =>
+ Math.max(0, count + (nextLiked ? -1 : 1)),
+ );
+ });
likePopTimeoutRef.current = window.setTimeout(() => {
likePopTimeoutRef.current = null;
setIsLikeButtonPopping(false);
}, 120);
};
+ React.useEffect(() => {
+ setIsLiked(viewerLiked);
+ }, [viewerLiked]);
+
+ React.useEffect(() => {
+ setLocalLikeCount(likeCount);
+ }, [likeCount]);
+
React.useEffect(
() => () => {
if (likePopTimeoutRef.current != null)
@@ -328,9 +239,11 @@ const FeedItem: React.FC<FeedItemProps> = ({
borderRadius: "50%",
border: 0,
cursor: onOpenFriend ? "pointer" : "default",
- display: "block",
+ display: "flex",
flexShrink: 0,
height: feedAvatarSize,
+ alignItems: "center",
+ justifyContent: "center",
overflow: "hidden",
p: 0,
width: feedAvatarSize,
@@ -340,18 +253,33 @@ const FeedItem: React.FC<FeedItemProps> = ({
},
}}
>
- <Box
- component="img"
- alt=""
- src={avatarUrl}
- sx={{
- display: "block",
- height: "100%",
- objectFit: "cover",
- objectPosition: "center",
- width: "100%",
- }}
- />
+ {avatarUrl ? (
+ <Box
+ component="img"
+ alt=""
+ src={avatarUrl}
+ sx={{
+ display: "block",
+ height: "100%",
+ objectFit: "cover",
+ objectPosition: "center",
+ width: "100%",
+ }}
+ />
+ ) : (
+ <Box
+ sx={{
+ color: green,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 9,
+ fontWeight: 800,
+ lineHeight: 1,
+ }}
+ >
+ {initialsFor(name)}
+ </Box>
+ )}
</Box>
<Box
component="button"
@@ -493,10 +421,16 @@ const FeedItem: React.FC<FeedItemProps> = ({
};
export const HomeScreen: React.FC<HomeScreenProps> = ({
+ feedItems,
friendsCount,
+ isFeedLoading = false,
+ onCreatePost,
+ onLoadPostLikers,
onOpenFriend,
onOpenNotifications,
onOpenProfile,
+ onSetPostLiked,
+ onShareProfileLink,
profile,
}) => {
const [selectedViewer, setSelectedViewer] =
@@ -504,13 +438,13 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
const postInputRef = React.useRef<HTMLInputElement | null>(null);
const localPostObjectUrlsRef = React.useRef<Set<string>>(new Set());
const selectedPhotoFriendID = selectedViewer?.photo.friendID;
- const feedItems = showMockFeedData ? sampleFeedItems : [];
const hasFeedItems = feedItems.length > 0;
const emptyFeedMessage =
- friendsCount == 0
- ? "When you add friends, their posts will appear here."
- : "When your friends share posts, they'll appear here.";
- const profileLink = profileLinkForUsername(profile.username.trim());
+ isFeedLoading
+ ? "Loading posts..."
+ : friendsCount == 0
+ ? "When you add friends, their posts will appear here."
+ : "When your friends share posts, they'll appear here.";
const initialsSource = profile.fullName.trim() || profile.username.trim();
const initials = initialsFor(initialsSource);
const revokeLocalPostObjectUrl = React.useCallback((objectUrl?: string) => {
@@ -551,6 +485,8 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
};
const shareProfileLink = async () => {
+ if (!onShareProfileLink) return;
+ const profileLink = await onShareProfileLink();
if (typeof navigator.share == "function") {
try {
await navigator.share({ url: profileLink });
@@ -579,6 +515,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
});
localPostObjectUrlsRef.current.add(localPost.objectUrl);
setSelectedViewer({
+ draftFile: file,
initialScreen: "photo",
localObjectUrl: localPost.objectUrl,
photo: localPost.photo,
@@ -823,7 +760,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
justifyContent: hasFeedItems ? "flex-start" : "center",
minHeight: "calc(100svh - 64px)",
pb: hasFeedItems ? "16px" : "56px",
- pt: hasFeedItems ? "12px" : 0,
+ pt: 0,
width: "100%",
}}
>
@@ -831,14 +768,22 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
feedItems.map((item) => (
<FeedItem
key={`${item.name}-${item.imageUrl}`}
- aspectRatio={item.aspectRatio}
- avatarUrl={item.avatarUrl}
+ aspectRatio={
+ item.width && item.height
+ ? item.width / item.height
+ : 1
+ }
+ avatarUrl={item.avatarUrl ?? ""}
friendID={item.friendID}
imageUrl={item.imageUrl}
+ likeCount={item.likeCount}
name={item.name}
onOpenFriend={onOpenFriend}
onOpenPhoto={openFeedPhoto}
+ onSetPostLiked={onSetPostLiked}
+ postId={item.postId}
timestampMs={item.timestampMs}
+ viewerLiked={item.viewerLiked}
/>
))
) : (
@@ -920,10 +865,6 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
</Box>
{selectedViewer && (
<SocialFileViewer
- currentUser={{
- avatarUrl: profile.avatarUrl,
- name: initialsSource,
- }}
initialScreen={selectedViewer.initialScreen}
photo={selectedViewer.photo}
postActionMode={
@@ -946,6 +887,31 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
}
: undefined
}
+ onLoadPostLikers={onLoadPostLikers}
+ onPublishDraftPost={
+ selectedViewer.draftFile && onCreatePost
+ ? async (caption) => {
+ const localObjectUrl =
+ selectedViewer.localObjectUrl;
+ const post = await onCreatePost(
+ selectedViewer.draftFile!,
+ caption,
+ );
+ revokeLocalPostObjectUrl(localObjectUrl);
+ setSelectedViewer((currentViewer) =>
+ currentViewer
+ ? {
+ initialScreen: "photo",
+ photo: post,
+ postActionMode:
+ "like-with-count",
+ }
+ : currentViewer,
+ );
+ }
+ : undefined
+ }
+ onSetPostLiked={onSetPostLiked}
/>
)}
</Box>
diff --git a/web/apps/social/src/screens/NotificationsScreen.tsx b/web/apps/social/src/screens/NotificationsScreen.tsx
index 2a73a22a3b..32fddb43e5 100644
--- a/web/apps/social/src/screens/NotificationsScreen.tsx
+++ b/web/apps/social/src/screens/NotificationsScreen.tsx
@@ -3,6 +3,7 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Box } from "@mui/material";
import {
SocialFileViewer,
+ type SocialLiker,
type SocialViewerPhoto,
} from "components/SocialFileViewer";
import type { FriendProfile } from "data/friends";
@@ -31,6 +32,7 @@ type NotificationType = "liked-post" | "added-friend";
interface SocialNotification {
actor: Pick<FriendProfile, "avatarUrl" | "fullName" | "id" | "username">;
id: string;
+ post?: SocialViewerPhoto;
postThumbnailUrl?: string;
timestampMs: number;
type: NotificationType;
@@ -40,6 +42,9 @@ interface NotificationsScreenProps {
onBack?: () => void;
onOpenFriend?: (friendID: string) => void;
profile: SetupProfile;
+ notifications: SocialNotification[];
+ onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;
+ onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
}
interface NotificationRowProps {
@@ -48,85 +53,8 @@ interface NotificationRowProps {
onOpenPost?: (notification: SocialNotification) => void;
}
-const minutesAgo = (minutes: number) => Date.now() - minutes * 60 * 1000;
-const hoursAgo = (hours: number) => minutesAgo(hours * 60);
-const daysAgo = (days: number) => hoursAgo(days * 24);
const microsForTimestamp = (timestampMs: number) => timestampMs * 1000;
-const sampleActors = {
- aparna: {
- avatarUrl: "/images/sample-feed-4.jpg",
- fullName: "Aparna Bhatnagar",
- id: "aparna-bhatnagar",
- username: "aparnab",
- },
- dev: {
- avatarUrl: "/images/sample-feed-1.jpg",
- fullName: "Dev Shah",
- id: "dev-shah",
- username: "devshah",
- },
- isha: {
- avatarUrl: "/images/sample-feed-2.jpg",
- fullName: "Isha Mehta",
- id: "isha-mehta",
- username: "ishamehta",
- },
- kabir: {
- avatarUrl: "/images/sample-avatar.jpg",
- fullName: "Kabir Menon",
- id: "kabir-menon",
- username: "kabirmenon",
- },
- mira: {
- avatarUrl: "/images/sample-feed-3.jpg",
- fullName: "Mira Sen",
- id: "mira-sen",
- username: "mirasen",
- },
- nikhil: {
- avatarUrl: "/images/sample-feed-5.jpg",
- fullName: "Nikhil Rao",
- id: "nikhil-rao",
- username: "nikhilrao",
- },
- riya: {
- avatarUrl: "/images/sample-feed-6.jpg",
- fullName: "Riya Kapoor",
- id: "riya-kapoor",
- username: "riyakapoor",
- },
-} satisfies Record<string, SocialNotification["actor"]>;
-
-const sampleNotifications: SocialNotification[] = [
- {
- actor: sampleActors.mira,
- id: "mira-liked-post",
- postThumbnailUrl: "/images/sample-feed-1.jpg",
- timestampMs: minutesAgo(12),
- type: "liked-post",
- },
- {
- actor: sampleActors.dev,
- id: "dev-added-friend",
- timestampMs: hoursAgo(8),
- type: "added-friend",
- },
- {
- actor: sampleActors.kabir,
- id: "kabir-liked-post",
- postThumbnailUrl: "/images/sample-feed-portrait-1.jpg",
- timestampMs: daysAgo(2),
- type: "liked-post",
- },
- {
- actor: sampleActors.mira,
- id: "mira-added-friend",
- timestampMs: daysAgo(8),
- type: "added-friend",
- },
-];
-
const LikedPhotoIcon: React.FC = () => (
<svg
width="15"
@@ -413,8 +341,11 @@ const NotificationRow: React.FC<NotificationRowProps> = ({
};
export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
+ notifications,
onBack,
+ onLoadPostLikers,
onOpenFriend,
+ onSetPostLiked,
profile,
}) => {
const [selectedPost, setSelectedPost] =
@@ -423,13 +354,15 @@ export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
const openPost = (notification: SocialNotification) => {
if (!notification.postThumbnailUrl) return;
- setSelectedPost({
- alt: `${profileName} post`,
- avatarUrl: profile.avatarUrl,
- imageUrl: notification.postThumbnailUrl,
- name: profileName,
- timestampMs: notification.timestampMs,
- });
+ setSelectedPost(
+ notification.post ?? {
+ alt: `${profileName} post`,
+ avatarUrl: profile.avatarUrl,
+ imageUrl: notification.postThumbnailUrl,
+ name: profileName,
+ timestampMs: notification.timestampMs,
+ },
+ );
};
return (
@@ -527,7 +460,7 @@ export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
width: "100%",
}}
>
- {sampleNotifications.map((notification) => (
+ {notifications.map((notification) => (
<NotificationRow
key={notification.id}
notification={notification}
@@ -539,13 +472,11 @@ export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
</Box>
{selectedPost && (
<SocialFileViewer
- currentUser={{
- avatarUrl: profile.avatarUrl,
- name: profileName,
- }}
onClose={() => setSelectedPost(null)}
+ onLoadPostLikers={onLoadPostLikers}
photo={selectedPost}
postActionMode="like-with-count"
+ onSetPostLiked={onSetPostLiked}
/>
)}
</Box>
diff --git a/web/apps/social/src/screens/ProfileScreen.tsx b/web/apps/social/src/screens/ProfileScreen.tsx
index cae029544c..7398eeb6b3 100644
--- a/web/apps/social/src/screens/ProfileScreen.tsx
+++ b/web/apps/social/src/screens/ProfileScreen.tsx
@@ -8,6 +8,7 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Box, Menu, MenuItem } from "@mui/material";
import {
SocialFileViewer,
+ type SocialLiker,
type SocialViewerPhoto,
type SocialViewerPostActionMode,
} from "components/SocialFileViewer";
@@ -19,7 +20,6 @@ import {
createLocalPostPhoto,
type LocalPostPhotoDimensions,
} from "utils/localPostPhoto";
-import { profileLinkForUsername } from "utils/profileLink";
import { firstNameFrom, initialsFor } from "utils/socialDisplay";
export const profileBackground = "#FFFFFF";
@@ -37,107 +37,36 @@ const profileCoverHeight =
profileHeaderHeight + profileAvatarTopOffset + profileAvatarSize / 2;
const photoMasonryGap = "3px";
const photoMasonryRadius = "12px";
-const showMockProfilePosts =
- process.env.NEXT_PUBLIC_HIDE_SOCIAL_MOCK_PROFILE_POSTS != "true";
-
interface ProfilePhotoDimensions {
height: number;
width: number;
}
-interface SampleProfilePhoto extends ProfilePhotoDimensions {
- imageUrl: string;
-}
-
-const samplePhotos = [
- { height: 680, imageUrl: "/images/sample-feed-1.jpg", width: 900 },
- {
- height: 1020,
- imageUrl: "/images/sample-feed-portrait-1.jpg",
- width: 680,
- },
- { height: 680, imageUrl: "/images/sample-feed-5.jpg", width: 900 },
- {
- height: 1020,
- imageUrl: "/images/sample-feed-portrait-2.jpg",
- width: 680,
- },
- { height: 680, imageUrl: "/images/sample-feed-2.jpg", width: 900 },
- {
- height: 1020,
- imageUrl: "/images/sample-feed-portrait-3.jpg",
- width: 680,
- },
- { height: 680, imageUrl: "/images/sample-feed-6.jpg", width: 900 },
- {
- height: 1020,
- imageUrl: "/images/sample-feed-portrait-4.jpg",
- width: 680,
- },
- { height: 680, imageUrl: "/images/sample-feed-3.jpg", width: 900 },
- {
- height: 1020,
- imageUrl: "/images/sample-feed-portrait-5.jpg",
- width: 680,
- },
- { height: 680, imageUrl: "/images/sample-feed-4.jpg", width: 900 },
- {
- height: 1020,
- imageUrl: "/images/sample-feed-portrait-6.jpg",
- width: 680,
- },
-] as const satisfies readonly SampleProfilePhoto[];
-
-const samplePostDateLabels = [
- "Today",
- "Yesterday",
- "Wed, Apr 29",
- "Tue, Apr 28",
- "Mon, Apr 27",
- "Sun, Apr 26",
- "Sat, Apr 25",
- "Fri, Apr 24",
- "Thu, Apr 23",
- "Wed, Apr 22",
-];
-
-const samplePostPhotoCounts = [4, 2, 1, 6, 10, 3, 8, 5, 7, 9];
-const minutesAgo = (minutes: number) => Date.now() - minutes * 60 * 1000;
-const hoursAgo = (hours: number) => minutesAgo(hours * 60);
-const daysAgo = (days: number) => hoursAgo(days * 24);
-
-const samplePostTimestampAt = (groupIndex: number, itemIndex: number) => {
- if (groupIndex == 0) return minutesAgo(18 + itemIndex * 12);
- if (groupIndex == 1) return hoursAgo(26 + itemIndex * 3);
- return daysAgo(groupIndex + 1) - itemIndex * 20 * 60 * 1000;
-};
-
-const samplePhotoAt = (index: number): SampleProfilePhoto =>
- samplePhotos[index % samplePhotos.length] ?? samplePhotos[0];
-
const photoAspectRatio = ({ height, width }: ProfilePhotoDimensions): number =>
height > 0 && width > 0 ? width / height : 1;
-const samplePostGroups = samplePostDateLabels.map((label, groupIndex) => ({
- label,
- items: Array.from(
- { length: samplePostPhotoCounts[groupIndex] ?? 1 },
- (_, itemIndex) => {
- const photo = samplePhotoAt(groupIndex + itemIndex);
- return {
- height: photo.height,
- id: `${groupIndex}-${itemIndex}`,
- imageUrl: photo.imageUrl,
- timestampMs: samplePostTimestampAt(groupIndex, itemIndex),
- width: photo.width,
- };
- },
- ),
-}));
+export interface ProfilePostItem {
+ avatarUrl?: string | null;
+ caption?: string;
+ friendID?: string;
+ height?: number;
+ id: string;
+ imageUrl: string;
+ likeCount?: number;
+ name?: string;
+ postId?: number;
+ timestampMs: number;
+ viewerLiked?: boolean;
+ width?: number;
+}
-type SamplePostItem = (typeof samplePostGroups)[number]["items"][number];
+export interface ProfilePostGroup {
+ items: ProfilePostItem[];
+ label: string;
+}
interface SelectedProfilePost {
+ draftFile?: File;
id: string;
localObjectUrl?: string;
photo: SocialViewerPhoto;
@@ -148,7 +77,7 @@ interface PostMasonryTile {
aspectRatio: number;
dimensions: ProfilePhotoDimensions;
index: number;
- item: SamplePostItem;
+ item: ProfilePostItem;
}
interface PostMasonryRow {
@@ -157,11 +86,14 @@ interface PostMasonryRow {
}
const buildPostMasonryRows = (
- items: SamplePostItem[],
+ items: ProfilePostItem[],
loadedDimensionsByURL: Record<string, ProfilePhotoDimensions>,
): PostMasonryRow[] => {
const tiles = items.map((item, index) => {
- const dimensions = loadedDimensionsByURL[item.imageUrl] ?? item;
+ const dimensions = loadedDimensionsByURL[item.imageUrl] ?? {
+ height: item.height ?? 1,
+ width: item.width ?? 1,
+ };
return {
aspectRatio: Math.max(0.1, photoAspectRatio(dimensions)),
dimensions,
@@ -199,22 +131,36 @@ const preferredPostMasonryRowSize = (remainingTiles: number) => {
interface ProfileScreenProps {
friendsCount?: number;
headerVariant?: "friend" | "owner" | "public";
+ isPostsLoading?: boolean;
onAddFriend?: () => void;
onBack?: () => void;
+ onCreatePost?: (file: File, caption: string) => Promise<SocialViewerPhoto>;
+ onDeletePost?: (postId: number) => Promise<void> | void;
+ onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;
onOpenFriend?: (friendID: string) => void;
onOpenFriends?: () => void;
onOpenSettings?: () => void;
+ onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
+ onShareProfileLink?: () => Promise<string>;
+ postGroups?: ProfilePostGroup[];
profile: SetupProfile;
}
export const ProfileScreen: React.FC<ProfileScreenProps> = ({
- friendsCount = 7,
+ friendsCount = 0,
headerVariant = "owner",
+ isPostsLoading = false,
onAddFriend,
onBack,
+ onCreatePost,
+ onDeletePost,
+ onLoadPostLikers,
onOpenFriend,
onOpenFriends,
onOpenSettings,
+ onSetPostLiked,
+ onShareProfileLink,
+ postGroups = [],
profile,
}) => {
const [profileActionsAnchor, setProfileActionsAnchor] =
@@ -232,11 +178,10 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
const isOwnerProfile = headerVariant == "owner";
const isFriendProfile = headerVariant == "friend";
const displayName = profile.fullName.trim() || profile.username.trim();
- const profileLink = profileLinkForUsername(profile.username.trim());
const firstName = firstNameFrom(displayName);
const initialsSource = displayName || profile.username.trim();
const initials = initialsFor(initialsSource);
- const visiblePostGroups = (showMockProfilePosts ? samplePostGroups : [])
+ const visiblePostGroups = postGroups
.map((group) => ({
...group,
items: group.items.filter((item) => !deletedPostIDs.has(item.id)),
@@ -320,6 +265,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
});
localPostObjectUrlsRef.current.add(localPost.objectUrl);
setSelectedPost({
+ draftFile: file,
id: `local-${localPost.photo.timestampMs}`,
localObjectUrl: localPost.objectUrl,
photo: localPost.photo,
@@ -329,11 +275,14 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
const copyProfileURL = async () => {
closeProfileActions();
- await navigator.clipboard.writeText(profileLink);
+ if (!onShareProfileLink) return;
+ await navigator.clipboard.writeText(await onShareProfileLink());
};
const shareProfile = async () => {
closeProfileActions();
+ if (!onShareProfileLink) return;
+ const profileLink = await onShareProfileLink();
if (typeof navigator.share == "function") {
try {
@@ -348,9 +297,12 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
await navigator.clipboard.writeText(profileLink);
};
- const deleteSelectedPost = () => {
+ const deleteSelectedPost = async () => {
if (!selectedPost) return;
+ if (selectedPost.photo.postId && onDeletePost) {
+ await onDeletePost(selectedPost.photo.postId);
+ }
setDeletedPostIDs((currentPostIDs) => {
const nextPostIDs = new Set(currentPostIDs);
nextPostIDs.add(selectedPost.id);
@@ -1037,9 +989,15 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
height: dimensions.height,
imageUrl:
item.imageUrl,
+ likeCount:
+ item.likeCount,
name: displayName,
+ postId:
+ item.postId,
timestampMs:
item.timestampMs,
+ viewerLiked:
+ item.viewerLiked,
width: dimensions.width,
},
},
@@ -1147,11 +1105,13 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
maxWidth: isOwnerProfile ? 230 : 250,
}}
>
- {isOwnerProfile
- ? "Your profile is looking empty. Share something with your friends."
- : `${firstName} hasn't posted anything yet.`}
+ {isPostsLoading
+ ? "Loading posts..."
+ : isOwnerProfile
+ ? "Your profile is looking empty. Share something with your friends."
+ : `${firstName} hasn't posted anything yet.`}
</Box>
- {isOwnerProfile && (
+ {isOwnerProfile && !isPostsLoading && (
<Box
component="button"
type="button"
@@ -1195,10 +1155,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
</Box>
{selectedPost && (
<SocialFileViewer
- currentUser={{
- avatarUrl: profile.avatarUrl,
- name: displayName,
- }}
photo={selectedPost.photo}
postActionMode={
selectedPost.postActionMode ??
@@ -1208,6 +1164,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
onDeletePost={
isOwnerProfile ? deleteSelectedPost : undefined
}
+ onLoadPostLikers={onLoadPostLikers}
onOpenFriend={
onOpenFriend
? (friendID) => {
@@ -1217,6 +1174,27 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
: undefined
}
onOpenProfile={closeSelectedPost}
+ onPublishDraftPost={
+ selectedPost.draftFile && onCreatePost
+ ? async (caption) => {
+ const localObjectUrl =
+ selectedPost.localObjectUrl;
+ const post = await onCreatePost(
+ selectedPost.draftFile!,
+ caption,
+ );
+ revokeLocalPostObjectUrl(localObjectUrl);
+ setSelectedPost({
+ id: String(
+ post.postId ?? post.imageUrl,
+ ),
+ photo: post,
+ postActionMode: "like-with-count",
+ });
+ }
+ : undefined
+ }
+ onSetPostLiked={onSetPostLiked}
/>
)}
</Box>
diff --git a/web/apps/social/src/screens/PublicProfileScreen.tsx b/web/apps/social/src/screens/PublicProfileScreen.tsx
index e7ccf3b136..415a10a5b5 100644
--- a/web/apps/social/src/screens/PublicProfileScreen.tsx
+++ b/web/apps/social/src/screens/PublicProfileScreen.tsx
@@ -1,19 +1,28 @@
import React from "react";
-import { ProfileScreen } from "screens/ProfileScreen";
+import { ProfileScreen, type ProfilePostGroup } from "screens/ProfileScreen";
import type { SetupProfile } from "screens/SetupProfileScreen";
interface PublicProfileScreenProps {
+ friendsCount?: number;
+ isPostsLoading?: boolean;
onAddFriend?: () => void;
+ postGroups?: ProfilePostGroup[];
profile: SetupProfile;
}
export const PublicProfileScreen: React.FC<PublicProfileScreenProps> = ({
+ friendsCount,
+ isPostsLoading,
onAddFriend,
+ postGroups,
profile,
}) => (
<ProfileScreen
+ friendsCount={friendsCount}
headerVariant="public"
+ isPostsLoading={isPostsLoading}
onAddFriend={onAddFriend}
+ postGroups={postGroups}
profile={profile}
/>
);
diff --git a/web/apps/social/src/screens/ShareProfileLinkScreen.tsx b/web/apps/social/src/screens/ShareProfileLinkScreen.tsx
index eca72e2835..e52442b4f5 100644
--- a/web/apps/social/src/screens/ShareProfileLinkScreen.tsx
+++ b/web/apps/social/src/screens/ShareProfileLinkScreen.tsx
@@ -3,7 +3,6 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Box } from "@mui/material";
import React, { useState } from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
-import { profileLinkForUsername } from "utils/profileLink";
import { initialsFor } from "utils/socialDisplay";
export const shareProfileLinkBackground = "#FAFAFA";
@@ -17,9 +16,13 @@ const iconFill = "#F0F0F0";
const actionRowHover = "#F5F5F5";
interface ShareProfileLinkScreenProps {
+ errorMessage?: string;
+ isLinkLoading?: boolean;
onBack: () => void;
onDone?: () => void;
+ onRetry?: () => void;
profile: SetupProfile;
+ profileLink?: string;
}
interface ActionRowProps {
@@ -165,23 +168,28 @@ const ActionRow: React.FC<ActionRowProps> = ({
);
export const ShareProfileLinkScreen: React.FC<ShareProfileLinkScreenProps> = ({
+ errorMessage,
+ isLinkLoading = false,
onBack,
onDone,
+ onRetry,
profile,
+ profileLink,
}) => {
const [copied, setCopied] = useState(false);
- const profileLink = profileLinkForUsername(profile.username.trim());
const displayName = profile.fullName.trim() || profile.username.trim();
const initialsSource = displayName || profile.username.trim();
const initials = initialsFor(initialsSource);
const copyProfileLink = async () => {
+ if (!profileLink) return;
await navigator.clipboard.writeText(profileLink);
setCopied(true);
window.setTimeout(() => setCopied(false), 1200);
};
const shareProfileLink = async () => {
+ if (!profileLink) return;
const shareData = { url: profileLink };
if (typeof navigator.share == "function") {
@@ -376,8 +384,32 @@ export const ShareProfileLinkScreen: React.FC<ShareProfileLinkScreenProps> = ({
width: "100%",
}}
>
- {profileLink}
+ {isLinkLoading
+ ? "Creating invite link..."
+ : profileLink || "Invite link unavailable"}
</Box>
+ {errorMessage && (
+ <Box
+ component="button"
+ type="button"
+ onClick={onRetry}
+ sx={{
+ bgcolor: "transparent",
+ border: 0,
+ color: green,
+ cursor: onRetry ? "pointer" : "default",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 600,
+ lineHeight: "18px",
+ mt: "10px",
+ p: 0,
+ }}
+ >
+ {errorMessage}
+ </Box>
+ )}
<Box
component="p"
sx={{
diff --git a/web/apps/social/src/screens/VerifyEmailScreen.tsx b/web/apps/social/src/screens/VerifyEmailScreen.tsx
index 8f55b5eed3..aa2082eb91 100644
--- a/web/apps/social/src/screens/VerifyEmailScreen.tsx
+++ b/web/apps/social/src/screens/VerifyEmailScreen.tsx
@@ -10,7 +10,6 @@ const textBase = "#000";
const textMuted = "#666";
const textLight = "#969696";
const warning = "#F63A3A";
-const mockVerificationCode = "888888";
const verifyEmailFormID = "social-verify-email-form";
interface VerifyEmailScreenProps {
@@ -121,7 +120,7 @@ const OtpInput: React.FC<OtpInputProps> = ({
export const VerifyEmailScreen: React.FC<VerifyEmailScreenProps> = ({
email,
errorMessage,
- initialCode = mockVerificationCode,
+ initialCode = "",
isSubmitting = false,
onBack,
onChangeEmail,
diff --git a/web/apps/social/src/services/socialInvite.ts b/web/apps/social/src/services/socialInvite.ts
new file mode 100644
index 0000000000..520c9782b4
--- /dev/null
+++ b/web/apps/social/src/services/socialInvite.ts
@@ -0,0 +1,60 @@
+export interface PendingSocialInvite {
+ accessKey: string;
+ wallUsername: string;
+}
+
+const pendingSocialInviteKey = "socialPendingInvite";
+const socialInviteAccessKeyPattern = /^[0-9A-Za-z]{12}$/;
+
+const isPendingSocialInvite = (value: unknown): value is PendingSocialInvite => {
+ if (!value || typeof value != "object") return false;
+ const candidate = value as Record<string, unknown>;
+ return (
+ typeof candidate.accessKey == "string" &&
+ typeof candidate.wallUsername == "string" &&
+ candidate.accessKey.trim().length > 0 &&
+ candidate.wallUsername.trim().length > 0
+ );
+};
+
+export const savePendingSocialInvite = (invite: PendingSocialInvite) => {
+ sessionStorage.setItem(pendingSocialInviteKey, JSON.stringify(invite));
+};
+
+export const savedPendingSocialInvite = () => {
+ const saved = sessionStorage.getItem(pendingSocialInviteKey);
+ if (!saved) return undefined;
+
+ try {
+ const parsed: unknown = JSON.parse(saved);
+ return isPendingSocialInvite(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const clearPendingSocialInvite = () => {
+ sessionStorage.removeItem(pendingSocialInviteKey);
+};
+
+export const socialInviteFromLocation = (): PendingSocialInvite | null => {
+ const match = /^\/([^/]+)\/?$/.exec(window.location.pathname);
+ const encodedAccessKey = window.location.hash.slice(1).trim();
+ if (!match || !encodedAccessKey) return null;
+
+ try {
+ const accessKey = decodeURIComponent(encodedAccessKey).trim();
+ const wallUsername = decodeURIComponent(match[1] ?? "").trim();
+ return socialInviteAccessKeyPattern.test(accessKey) && wallUsername
+ ? { accessKey, wallUsername }
+ : null;
+ } catch {
+ return null;
+ }
+};
+
+export const socialInviteURL = ({
+ accessKey,
+ wallUsername,
+}: PendingSocialInvite) =>
+ `${window.location.origin}/${encodeURIComponent(wallUsername)}#${encodeURIComponent(accessKey)}`;
diff --git a/web/apps/social/src/services/socialProfile.ts b/web/apps/social/src/services/socialProfile.ts
index 053bd50730..de557d12a2 100644
--- a/web/apps/social/src/services/socialProfile.ts
+++ b/web/apps/social/src/services/socialProfile.ts
@@ -108,7 +108,7 @@ const wallHTTPStatus = (error: unknown) => {
return typeof status == "number" ? status : undefined;
};
-const openCurrentWallContext = async () => {
+export const openCurrentWallContext = async () => {
const [authToken, baseUrl, masterKeyB64] = await Promise.all([
savedAuthToken(),
apiOrigin(),
@@ -134,7 +134,7 @@ const openCurrentWallContext = async () => {
});
};
-const ensureCurrentWallContext = async () => {
+export const ensureCurrentWallContext = async () => {
const ctx = await openCurrentWallContext();
if (!ctx) throw new Error("Please sign in again.");
return ctx;
diff --git a/web/apps/social/src/services/socialWall.ts b/web/apps/social/src/services/socialWall.ts
new file mode 100644
index 0000000000..38d437a4e4
--- /dev/null
+++ b/web/apps/social/src/services/socialWall.ts
@@ -0,0 +1,629 @@
+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
+import { getKV, removeKV, setKV } from "ente-base/kv";
+import { apiOrigin } from "ente-base/origins";
+import type { WallAccountCtxHandle, WallLinkCtxHandle } from "ente-wasm";
+import { loadEnteWasm } from "ente-wasm/load";
+import type { FriendProfile } from "data/friends";
+import type { PendingSocialInvite } from "services/socialInvite";
+import { socialInviteURL } from "services/socialInvite";
+import { ensureCurrentWallContext } from "services/socialProfile";
+
+interface WallAvatar {
+ objectKey: string;
+ size?: number;
+ updatedAt?: string;
+}
+
+interface WallProfilePayload {
+ displayName?: unknown;
+ fullName?: unknown;
+ username?: unknown;
+}
+
+interface WallProfileResponse {
+ avatar?: WallAvatar;
+ friends?: number;
+ profile: string;
+ updatedAt?: string;
+ version?: number;
+ wallId: string;
+ wallSlug: string;
+}
+
+interface WallActor {
+ avatar?: WallAvatar;
+ friends?: number;
+ posts?: number;
+ profile?: string;
+ userId?: number;
+ wallId: string;
+ wallSlug: string;
+}
+
+interface WallPostObject {
+ height?: number;
+ mediaType?: string;
+ objectKey: string;
+ width?: number;
+}
+
+interface WallPost {
+ author: WallActor;
+ caption?: string;
+ createdAt: string;
+ likes: number;
+ objects?: WallPostObject[];
+ postId: number;
+ viewerLiked: boolean;
+ wallId: string;
+ wallSlug: string;
+}
+
+interface WallPostPage {
+ items?: WallPost[];
+ nextCursor?: string;
+}
+
+interface WallFriend {
+ createdAt: string;
+ friend: WallActor;
+ shareKeyVersion: number;
+}
+
+interface WallNotification {
+ actor: WallActor;
+ createdAt: string;
+ id: string;
+ post?: {
+ author: WallActor;
+ objects?: WallPostObject[];
+ postId: number;
+ wallId: string;
+ wallSlug: string;
+ };
+ type: "likedPost" | "addedYouAsFriend";
+}
+
+interface WallNotificationPage {
+ items?: WallNotification[];
+ nextCursor?: string;
+}
+
+interface WallPostLikerPage {
+ likers?: { actor: WallActor; createdAt: string }[];
+ nextCursor?: string;
+}
+
+interface WallLinkStatus {
+ active?: boolean;
+ keyVersion?: number;
+ wallId?: string;
+ wallSlug?: string;
+}
+
+interface StoredSocialWallLink {
+ accessKey: string;
+ keyVersion: number;
+ wallId: string;
+ wallSlug: string;
+ wallUsername: string;
+}
+
+export interface SocialWallPost {
+ avatarUrl?: string | null;
+ caption?: string;
+ friendID: string;
+ height?: number;
+ imageUrl: string;
+ likeCount: number;
+ name: string;
+ postId: number;
+ timestampMs: number;
+ viewerLiked: boolean;
+ wallId: string;
+ width?: number;
+}
+
+export interface SocialWallPostPage {
+ items: SocialWallPost[];
+ nextCursor?: string;
+}
+
+export interface SocialWallNotification {
+ actor: FriendProfile;
+ id: string;
+ post?: SocialWallPost;
+ timestampMs: number;
+ type: "added-friend" | "liked-post";
+}
+
+export interface SocialWallNotificationPage {
+ items: SocialWallNotification[];
+ nextCursor?: string;
+}
+
+export interface SocialWallLink {
+ accessKey: string;
+ url: string;
+ wallId: string;
+ wallSlug: string;
+ wallUsername: string;
+}
+
+export interface SocialLiker {
+ avatarUrl?: string | null;
+ friendID?: string;
+ id: string;
+ name: string;
+}
+
+const socialWallLinkKey = (wallId: string) =>
+ `social:wall-link:${encodeURIComponent(wallId)}`;
+
+const isStoredSocialWallLink = (
+ value: unknown,
+ wallId: string,
+): value is StoredSocialWallLink => {
+ if (!value || typeof value != "object") return false;
+ const link = value as Partial<StoredSocialWallLink>;
+ return (
+ link.wallId == wallId &&
+ typeof link.accessKey == "string" &&
+ /^[0-9A-Za-z]{12}$/.test(link.accessKey) &&
+ typeof link.keyVersion == "number" &&
+ typeof link.wallSlug == "string" &&
+ typeof link.wallUsername == "string"
+ );
+};
+
+const socialWallLinkFromStored = (
+ stored: StoredSocialWallLink,
+): SocialWallLink => ({
+ accessKey: stored.accessKey,
+ url: socialInviteURL({
+ accessKey: stored.accessKey,
+ wallUsername: stored.wallUsername || stored.wallSlug,
+ }),
+ wallId: stored.wallId,
+ wallSlug: stored.wallSlug,
+ wallUsername: stored.wallUsername || stored.wallSlug,
+});
+
+const parseWallProfilePayload = (profile: string): WallProfilePayload => {
+ if (!profile.trim()) return {};
+ try {
+ const parsed: unknown = JSON.parse(profile);
+ return parsed && typeof parsed == "object"
+ ? (parsed as WallProfilePayload)
+ : {};
+ } catch {
+ return {};
+ }
+};
+
+const textField = (value: unknown) =>
+ typeof value == "string" ? value.trim() : "";
+
+const timestampMsFromWallDate = (value: string) => {
+ const parsed = Date.parse(value);
+ return Number.isFinite(parsed) ? parsed : Date.now();
+};
+
+const blobURLForBytes = (bytes: Uint8Array, mediaType?: string) =>
+ URL.createObjectURL(new Blob([bytes], { type: mediaType || undefined }));
+
+const actorProfile = (actor: WallActor): FriendProfile => {
+ const payload = parseWallProfilePayload(actor.profile ?? "");
+ const fullName =
+ textField(payload.fullName) ||
+ textField(payload.displayName) ||
+ actor.wallSlug;
+ const username = actor.wallSlug;
+
+ return {
+ avatarUrl: null,
+ friendsCount: actor.friends ?? 0,
+ fullName,
+ id: actor.wallId || username,
+ username,
+ wallId: actor.wallId,
+ wallSlug: actor.wallSlug,
+ };
+};
+
+const profileFromWallProfile = (
+ wallProfile: WallProfileResponse,
+): FriendProfile => {
+ const payload = parseWallProfilePayload(wallProfile.profile);
+ const fullName =
+ textField(payload.fullName) ||
+ textField(payload.displayName) ||
+ wallProfile.wallSlug;
+
+ return {
+ avatarUrl: null,
+ friendsCount: wallProfile.friends ?? 0,
+ fullName,
+ id: wallProfile.wallId || wallProfile.wallSlug,
+ username: wallProfile.wallSlug,
+ wallId: wallProfile.wallId,
+ wallSlug: wallProfile.wallSlug,
+ };
+};
+
+const accountAvatarURL = async (
+ ctx: WallAccountCtxHandle,
+ wallId: string | undefined,
+ avatar: WallAvatar | undefined,
+) => {
+ if (!wallId || !avatar?.objectKey) return null;
+ return blobURLForBytes(
+ await ctx.download_wall_avatar(wallId, avatar.objectKey),
+ );
+};
+
+const linkAvatarURL = async (
+ ctx: WallLinkCtxHandle,
+ avatar: WallAvatar | undefined,
+) => {
+ if (!avatar?.objectKey) return null;
+ return blobURLForBytes(await ctx.download_wall_avatar(avatar.objectKey));
+};
+
+const firstObject = (post: Pick<WallPost, "objects">) =>
+ post.objects?.find((object) => object.objectKey.trim()) ?? null;
+
+const postFromAccountPost = async (
+ ctx: WallAccountCtxHandle,
+ post: WallPost,
+): Promise<SocialWallPost | null> => {
+ const object = firstObject(post);
+ if (!object) return null;
+
+ const author = actorProfile(post.author);
+ author.avatarUrl = await accountAvatarURL(
+ ctx,
+ post.author.wallId,
+ post.author.avatar,
+ );
+
+ const imageUrl = blobURLForBytes(
+ await ctx.download_post_asset(BigInt(post.postId), object.objectKey),
+ object.mediaType,
+ );
+ return {
+ avatarUrl: author.avatarUrl,
+ caption: post.caption,
+ friendID: author.id,
+ height: object.height,
+ imageUrl,
+ likeCount: post.likes,
+ name: author.fullName || author.username,
+ postId: post.postId,
+ timestampMs: timestampMsFromWallDate(post.createdAt),
+ viewerLiked: post.viewerLiked,
+ wallId: post.wallId,
+ width: object.width,
+ };
+};
+
+const postFromLinkPost = async (
+ ctx: WallLinkCtxHandle,
+ post: WallPost,
+): Promise<SocialWallPost | null> => {
+ const object = firstObject(post);
+ if (!object) return null;
+
+ const author = actorProfile(post.author);
+ author.avatarUrl = await linkAvatarURL(ctx, post.author.avatar);
+
+ const imageUrl = blobURLForBytes(
+ await ctx.download_post_asset(BigInt(post.postId), object.objectKey),
+ object.mediaType,
+ );
+ return {
+ avatarUrl: author.avatarUrl,
+ caption: post.caption,
+ friendID: author.id,
+ height: object.height,
+ imageUrl,
+ likeCount: post.likes,
+ name: author.fullName || author.username,
+ postId: post.postId,
+ timestampMs: timestampMsFromWallDate(post.createdAt),
+ viewerLiked: post.viewerLiked,
+ wallId: post.wallId,
+ width: object.width,
+ };
+};
+
+const postPageFromAccountPage = async (
+ ctx: WallAccountCtxHandle,
+ page: WallPostPage,
+): Promise<SocialWallPostPage> => {
+ const items = (
+ await Promise.all(
+ (page.items ?? []).map((post) => postFromAccountPost(ctx, post)),
+ )
+ ).filter((post): post is SocialWallPost => Boolean(post));
+ return { items, nextCursor: page.nextCursor || undefined };
+};
+
+const postPageFromLinkPage = async (
+ ctx: WallLinkCtxHandle,
+ page: WallPostPage,
+): Promise<SocialWallPostPage> => {
+ const items = (
+ await Promise.all(
+ (page.items ?? []).map((post) => postFromLinkPost(ctx, post)),
+ )
+ ).filter((post): post is SocialWallPost => Boolean(post));
+ return { items, nextCursor: page.nextCursor || undefined };
+};
+
+export const createCurrentProfileLink = async (
+ wallId: string,
+): Promise<SocialWallLink> => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ const status = (await ctx.get_wall_link_status(
+ wallId,
+ )) as WallLinkStatus;
+ const stored = await getKV(socialWallLinkKey(wallId));
+ if (
+ status.active &&
+ isStoredSocialWallLink(stored, wallId) &&
+ stored.keyVersion == status.keyVersion
+ ) {
+ return socialWallLinkFromStored(stored);
+ }
+ if (!status.active) await removeKV(socialWallLinkKey(wallId));
+
+ const created = (await ctx.create_wall_link(wallId)) as {
+ accessKey: string;
+ keyVersion: number;
+ wallId: string;
+ wallSlug: string;
+ wallUsername: string;
+ };
+ const storedLink: StoredSocialWallLink = {
+ accessKey: created.accessKey,
+ keyVersion: created.keyVersion,
+ wallId: created.wallId,
+ wallSlug: created.wallSlug,
+ wallUsername: created.wallUsername || created.wallSlug,
+ };
+ await setKV(socialWallLinkKey(wallId), storedLink);
+ return {
+ accessKey: created.accessKey,
+ url: socialInviteURL(storedLink),
+ wallId: created.wallId,
+ wallSlug: created.wallSlug,
+ wallUsername: storedLink.wallUsername,
+ };
+ } finally {
+ ctx.free();
+ }
+};
+
+export const joinSocialInvite = async ({
+ accessKey,
+ wallUsername,
+}: PendingSocialInvite) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ await ctx.join_wall_link(wallUsername, accessKey);
+ } finally {
+ ctx.free();
+ }
+};
+
+export const loadCurrentWallFriends = async (wallId: string) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ const friends = (await ctx.list_wall_friends(wallId)) as WallFriend[];
+ return await Promise.all(
+ friends.map(async ({ friend }) => {
+ const profile = actorProfile(friend);
+ profile.avatarUrl = await accountAvatarURL(
+ ctx,
+ friend.wallId,
+ friend.avatar,
+ );
+ return profile;
+ }),
+ );
+ } finally {
+ ctx.free();
+ }
+};
+
+export const removeCurrentWallFriend = async (wallId: string) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ await ctx.remove_friend_by_wall(wallId);
+ } finally {
+ ctx.free();
+ }
+};
+
+export const loadCurrentFeedPage = async (
+ cursor?: string,
+): Promise<SocialWallPostPage> => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ return await postPageFromAccountPage(
+ ctx,
+ (await ctx.list_feed(cursor ?? null, 30)) as WallPostPage,
+ );
+ } finally {
+ ctx.free();
+ }
+};
+
+export const loadCurrentWallPostsPage = async (
+ wallId: string,
+ cursor?: string,
+): Promise<SocialWallPostPage> => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ return await postPageFromAccountPage(
+ ctx,
+ (await ctx.list_posts(wallId, cursor ?? null, 60)) as WallPostPage,
+ );
+ } finally {
+ ctx.free();
+ }
+};
+
+export const createCurrentPhotoPost = async ({
+ caption,
+ file,
+ wallId,
+}: {
+ caption?: string;
+ file: File;
+ wallId: string;
+}) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ const created = (await ctx.create_photo_post(
+ wallId,
+ bytes,
+ caption?.trim() || null,
+ null,
+ null,
+ file.type || null,
+ )) as WallPost;
+ return await postFromAccountPost(ctx, created);
+ } finally {
+ ctx.free();
+ }
+};
+
+export const setCurrentPostLiked = async (postId: number, liked: boolean) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ await ctx.like_post(BigInt(postId), liked);
+ } finally {
+ ctx.free();
+ }
+};
+
+export const loadCurrentPostLikers = async (postId: number) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ const page = (await ctx.list_post_likers(
+ BigInt(postId),
+ null,
+ 100,
+ )) as WallPostLikerPage;
+ return await Promise.all(
+ (page.likers ?? []).map(async ({ actor }) => {
+ const profile = actorProfile(actor);
+ profile.avatarUrl = await accountAvatarURL(
+ ctx,
+ actor.wallId,
+ actor.avatar,
+ );
+ return {
+ avatarUrl: profile.avatarUrl,
+ friendID: profile.id,
+ id: profile.id,
+ name: profile.fullName || profile.username,
+ };
+ }),
+ );
+ } finally {
+ ctx.free();
+ }
+};
+
+export const deleteCurrentPost = async (postId: number) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ await ctx.delete_post(BigInt(postId));
+ } finally {
+ ctx.free();
+ }
+};
+
+export const loadCurrentNotificationsPage =
+ async (): Promise<SocialWallNotificationPage> => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ const page = (await ctx.list_notifications(
+ null,
+ 50,
+ )) as WallNotificationPage;
+ const items = await Promise.all(
+ (page.items ?? []).map(async (notification) => {
+ const actor = actorProfile(notification.actor);
+ actor.avatarUrl = await accountAvatarURL(
+ ctx,
+ notification.actor.wallId,
+ notification.actor.avatar,
+ );
+ const postObject = notification.post
+ ? firstObject(notification.post)
+ : null;
+ const post =
+ notification.post && postObject
+ ? await postFromAccountPost(ctx, {
+ author: notification.post.author,
+ createdAt: notification.createdAt,
+ likes: 0,
+ objects: notification.post.objects,
+ postId: notification.post.postId,
+ viewerLiked: false,
+ wallId: notification.post.wallId,
+ wallSlug: notification.post.wallSlug,
+ })
+ : undefined;
+ const notificationType: SocialWallNotification["type"] =
+ notification.type == "addedYouAsFriend"
+ ? "added-friend"
+ : "liked-post";
+ return {
+ actor,
+ id: notification.id,
+ post: post ?? undefined,
+ timestampMs: timestampMsFromWallDate(
+ notification.createdAt,
+ ),
+ type: notificationType,
+ };
+ }),
+ );
+ return { items, nextCursor: page.nextCursor || undefined };
+ } finally {
+ ctx.free();
+ }
+ };
+
+export const loadPublicSocialInvite = async ({
+ accessKey,
+ wallUsername,
+}: PendingSocialInvite) => {
+ const { wall_open_link_ctx } = await loadEnteWasm();
+ const ctx = await wall_open_link_ctx({
+ accessKey,
+ baseUrl: await apiOrigin(),
+ clientPackage: clientPackageName,
+ clientVersion: isDesktop ? desktopAppVersion : undefined,
+ wallUsername,
+ });
+ try {
+ const wallProfile = (await ctx.get_wall_profile()) as WallProfileResponse;
+ const profile = profileFromWallProfile(wallProfile);
+ profile.avatarUrl = await linkAvatarURL(ctx, wallProfile.avatar);
+ const posts = await postPageFromLinkPage(
+ ctx,
+ (await ctx.list_posts(null, 60)) as WallPostPage,
+ );
+ return { posts: posts.items, profile };
+ } finally {
+ ctx.free();
+ }
+};
diff --git a/web/apps/social/src/state/socialAppState.tsx b/web/apps/social/src/state/socialAppState.tsx
index c9b31d3726..04f76db587 100644
--- a/web/apps/social/src/state/socialAppState.tsx
+++ b/web/apps/social/src/state/socialAppState.tsx
@@ -1,4 +1,4 @@
-import { sampleFriends, type FriendProfile } from "data/friends";
+import type { FriendProfile } from "data/friends";
import React, { createContext, useContext } from "react";
import type { SocialLoginCredentials } from "screens/LoginScreen";
import type { SetupProfile } from "screens/SetupProfileScreen";
@@ -33,10 +33,7 @@ export interface SocialAppState {
setSignupEmail: React.Dispatch<React.SetStateAction<string>>;
}
-export const showMockFriends =
- process.env.NEXT_PUBLIC_HIDE_SOCIAL_MOCK_FRIENDS != "true";
-
-export const initialFriends = () => (showMockFriends ? sampleFriends : []);
+export const initialFriends = (): FriendProfile[] => [];
export const SocialAppStateContext = createContext<SocialAppState | null>(null);
diff --git a/web/apps/social/src/utils/profileLink.ts b/web/apps/social/src/utils/profileLink.ts
deleted file mode 100644
index 214f995c65..0000000000
--- a/web/apps/social/src/utils/profileLink.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-const profileSecret = "5d2a9WhmD2NU";
-
-export const profileLinkForUsername = (username: string) =>
- `https://ente.gg/${encodeURIComponent(username || "anandbaburajan")}#${profileSecret}`;
diff --git a/web/apps/social/src/utils/socialWallDisplay.ts b/web/apps/social/src/utils/socialWallDisplay.ts
new file mode 100644
index 0000000000..224feaaa7d
--- /dev/null
+++ b/web/apps/social/src/utils/socialWallDisplay.ts
@@ -0,0 +1,72 @@
+import type { SocialViewerPhoto } from "components/SocialFileViewer";
+import type { ProfilePostGroup } from "screens/ProfileScreen";
+import type { SocialWallNotification, SocialWallPost } from "services/socialWall";
+
+export const socialPostToViewerPhoto = (
+ post: SocialWallPost,
+): SocialViewerPhoto => ({
+ alt: `${post.name} post`,
+ avatarUrl: post.avatarUrl,
+ caption: post.caption,
+ friendID: post.friendID,
+ height: post.height,
+ imageUrl: post.imageUrl,
+ likeCount: post.likeCount,
+ name: post.name,
+ postId: post.postId,
+ timestampMs: post.timestampMs,
+ viewerLiked: post.viewerLiked,
+ width: post.width,
+});
+
+const profilePostDateLabel = (timestampMs: number) => {
+ const date = new Date(timestampMs);
+ const today = new Date();
+ const yesterday = new Date(today);
+ yesterday.setDate(today.getDate() - 1);
+ if (date.toDateString() == today.toDateString()) return "Today";
+ if (date.toDateString() == yesterday.toDateString()) return "Yesterday";
+ return date.toLocaleDateString(
+ typeof navigator == "undefined" ? "en-US" : navigator.language,
+ { day: "numeric", month: "short", weekday: "short" },
+ );
+};
+
+export const profilePostGroupsFromPosts = (
+ posts: SocialWallPost[],
+): ProfilePostGroup[] => {
+ const groups = new Map<string, ProfilePostGroup>();
+ posts.forEach((post) => {
+ const label = profilePostDateLabel(post.timestampMs);
+ const group = groups.get(label) ?? { items: [], label };
+ group.items.push({
+ avatarUrl: post.avatarUrl,
+ caption: post.caption,
+ friendID: post.friendID,
+ height: post.height,
+ id: String(post.postId),
+ imageUrl: post.imageUrl,
+ likeCount: post.likeCount,
+ name: post.name,
+ postId: post.postId,
+ timestampMs: post.timestampMs,
+ viewerLiked: post.viewerLiked,
+ width: post.width,
+ });
+ groups.set(label, group);
+ });
+ return [...groups.values()];
+};
+
+export const notificationForScreen = (
+ notification: SocialWallNotification,
+) => ({
+ actor: notification.actor,
+ id: notification.id,
+ post: notification.post
+ ? socialPostToViewerPhoto(notification.post)
+ : undefined,
+ postThumbnailUrl: notification.post?.imageUrl,
+ timestampMs: notification.timestampMs,
+ type: notification.type,
+});
diff --git a/web/packages/wasm/src/wall.rs b/web/packages/wasm/src/wall.rs
index 7c2e19505b..8606bca042 100644
--- a/web/packages/wasm/src/wall.rs
+++ b/web/packages/wasm/src/wall.rs
@@ -128,6 +128,7 @@ struct WallProfileJs {
wall_id: String,
wall_slug: String,
version: i32,
+ friends: i64,
profile: String,
avatar: Option<ProfileAvatarResponse>,
updated_at: Option<String>,
@@ -263,6 +264,7 @@ fn profile_to_js(value: DecryptedWallProfile) -> Result<WallProfileJs, WasmWallE
wall_id: value.wall_id,
wall_slug: value.wall_slug,
version: value.version,
+ friends: value.friends,
profile: utf8_field(value.profile, "profile")?,
avatar: value.avatar,
updated_at: value.updated_at,
@@ -558,7 +560,7 @@ impl WallAccountCtxHandle {
swb::to_value(&self.inner.get_relationship(&target_wall_id).await?).map_err(Into::into)
}
- /// Create or rotate a shareable wall link.
+ /// Create a shareable wall link.
pub async fn create_wall_link(&self, wall_id: String) -> Result<JsValue, WasmWallError> {
swb::to_value(&created_link_to_js(
self.inner.create_wall_link(&wall_id).await?,