Keep one like per recording and float the playlist artwork picker
Build and Publish / Build and Publish Docker Image (push) Successful in 4m24s
Build and Publish / Build and Publish Docker Image (push) Successful in 4m24s
This commit is contained in:
1 parent
b584e660a4
commit
af38255440
20 files changed
+852
-266
No files matched your search
+5
-1
@@ -24,7 +24,11 @@
|
||||
artists are accessible from the account menu.
|
||||
- Playlist headers show release artwork as a collage and keep the pin on the
|
||||
right. Owners can rename inline, choose up to four images from the playlist,
|
||||
upload a cover, or restore the automatic collage.
|
||||
upload a cover, or restore the automatic collage. The artwork picker floats
|
||||
beside the cover and keeps the track list in place.
|
||||
- Liked songs now keeps one entry when several catalog rows share the same
|
||||
audio. Existing duplicate likes are repaired on upgrade. Different recordings
|
||||
with the same title can still be liked separately.
|
||||
- Track rows keep lyrics, popularity and playback controls aligned. The new
|
||||
actions menu includes sharing, playlists, queueing, track details, similarity
|
||||
search and downloading where available.
|
||||
|
||||
+82
-79
@@ -5,6 +5,8 @@
|
||||
//! protocol as the TUI clients on `furumi/sync/1` and maps operations into
|
||||
//! user-scoped Postgres state.
|
||||
|
||||
pub(crate) mod likes;
|
||||
|
||||
use music_dht::playback::{Announcement, Checkpoint, Config as PlaybackConfig, Engine};
|
||||
use std::collections::BTreeMap;
|
||||
use std::str::FromStr;
|
||||
@@ -539,16 +541,32 @@ pub async fn record_track_like(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
record_local_op(
|
||||
pool,
|
||||
let identity = ensure_identity(pool, user_id, "").await?;
|
||||
let mut tx = pool.begin().await?;
|
||||
likes::lock(&mut tx, user_id).await?;
|
||||
let aliases = likes::Aliases::load(&mut tx, &content_id).await?;
|
||||
// Another click may have committed between the web mutation and sync.
|
||||
if aliases.existing(&mut tx, user_id).await?.is_some() != liked {
|
||||
return Ok(());
|
||||
}
|
||||
let payload = SyncOpPayload::TrackLikeSet {
|
||||
content_id: content_id.clone(),
|
||||
liked,
|
||||
fed: fed.clone(),
|
||||
};
|
||||
let op = append_local_op(&mut tx, user_id, identity.device_id, payload).await?;
|
||||
store_like_state(
|
||||
&mut tx,
|
||||
&aliases,
|
||||
user_id,
|
||||
SyncOpPayload::TrackLikeSet {
|
||||
content_id,
|
||||
liked,
|
||||
fed,
|
||||
},
|
||||
&content_id,
|
||||
liked,
|
||||
fed.as_ref(),
|
||||
op.hlc_ms,
|
||||
&op.op_id,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -680,39 +698,14 @@ pub async fn record_content_playlist_add(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Reconciles content-addressed user state after a track becomes local.
|
||||
/// History is intentionally not touched: only actual web playback writes it.
|
||||
pub async fn materialize_content_state(
|
||||
/// Adds saved playlist items to the local catalog after the audio import commits.
|
||||
pub(super) async fn materialize_playlist_items(
|
||||
pool: &sqlx::PgPool,
|
||||
content_id: &str,
|
||||
track_id: i64,
|
||||
) -> Result<()> {
|
||||
let content_id =
|
||||
music_dht::normalize_content_id(content_id).context("invalid track content id")?;
|
||||
let likes = sqlx::query(
|
||||
"SELECT user_id, liked, hlc_ms
|
||||
FROM furumusic__fed_state_like WHERE content_id = $1",
|
||||
)
|
||||
.bind(&content_id)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
for row in likes {
|
||||
let user_id: i64 = row.get("user_id");
|
||||
let liked: bool = row.get("liked");
|
||||
if liked {
|
||||
sqlx::query(
|
||||
"INSERT INTO furumusic__user_liked_track
|
||||
(user_id, track_id, created_at)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (user_id, track_id) DO NOTHING",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(track_id)
|
||||
.bind(iso_from_ms(row.get("hlc_ms")))
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let playlist_items = sqlx::query(
|
||||
"SELECT i.user_id, i.playlist_id, i.position
|
||||
FROM furumusic__fed_state_playlist_item i
|
||||
@@ -742,14 +735,6 @@ pub async fn materialize_content_state(
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE furumusic__fed_state_like
|
||||
SET local_track_id = $2 WHERE content_id = $1",
|
||||
)
|
||||
.bind(&content_id)
|
||||
.bind(track_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE furumusic__fed_state_playlist_item
|
||||
SET local_track_id = $2 WHERE content_id = $1",
|
||||
@@ -1823,6 +1808,19 @@ async fn record_local_op(
|
||||
);
|
||||
}
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
let op = append_local_op(&mut tx, user_id, identity.device_id, payload).await?;
|
||||
tx.commit().await?;
|
||||
let _ = apply_op(pool, Arc::new(PlayerDeviceHub::default()), user_id, &op).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn append_local_op(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
user_id: i64,
|
||||
device_id: String,
|
||||
payload: SyncOpPayload,
|
||||
) -> Result<SyncOpWire> {
|
||||
let now = now_ms();
|
||||
let row = sqlx::query(
|
||||
"UPDATE furumusic__fed_device_identity
|
||||
@@ -1833,14 +1831,14 @@ async fn record_local_op(
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(now)
|
||||
.fetch_one(pool)
|
||||
.fetch_one(&mut *conn)
|
||||
.await?;
|
||||
let seq: i64 = row.get("local_seq");
|
||||
let hlc_ms: i64 = row.get("last_hlc_ms");
|
||||
let op_id = format!("{}:{seq}", identity.device_id);
|
||||
let op_id = format!("{device_id}:{seq}");
|
||||
let op = SyncOpWire {
|
||||
op_id,
|
||||
origin_device_id: identity.device_id,
|
||||
origin_device_id: device_id,
|
||||
seq,
|
||||
hlc_ms,
|
||||
payload,
|
||||
@@ -1861,7 +1859,7 @@ async fn record_local_op(
|
||||
.bind(op.hlc_ms)
|
||||
.bind(now_ms())
|
||||
.bind(op.payload.is_tombstone())
|
||||
.execute(pool)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO furumusic__fed_sync_vector (user_id, device_id, max_seq)
|
||||
@@ -1872,10 +1870,9 @@ async fn record_local_op(
|
||||
.bind(user_id)
|
||||
.bind(&op.origin_device_id)
|
||||
.bind(op.seq)
|
||||
.execute(pool)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
let _ = apply_op(pool, Arc::new(PlayerDeviceHub::default()), user_id, &op).await?;
|
||||
Ok(())
|
||||
Ok(op)
|
||||
}
|
||||
|
||||
pub(crate) async fn record_podcast_op(
|
||||
@@ -2218,14 +2215,42 @@ async fn apply_like_state(
|
||||
let Some(content_id) = music_dht::normalize_content_id(content_id) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut tx = pool.begin().await?;
|
||||
likes::lock(&mut tx, user_id).await?;
|
||||
let aliases = likes::Aliases::load(&mut tx, &content_id).await?;
|
||||
let applied = store_like_state(
|
||||
&mut tx,
|
||||
&aliases,
|
||||
user_id,
|
||||
&content_id,
|
||||
liked,
|
||||
fed,
|
||||
hlc_ms,
|
||||
op_id,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(applied)
|
||||
}
|
||||
|
||||
async fn store_like_state(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
aliases: &likes::Aliases,
|
||||
user_id: i64,
|
||||
content_id: &str,
|
||||
liked: bool,
|
||||
fed: Option<&SyncedFedTrack>,
|
||||
hlc_ms: i64,
|
||||
op_id: &str,
|
||||
) -> Result<bool> {
|
||||
let current = sqlx::query(
|
||||
"SELECT liked, hlc_ms, op_id
|
||||
FROM furumusic__fed_state_like
|
||||
WHERE user_id = $1 AND content_id = $2",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&content_id)
|
||||
.fetch_optional(pool)
|
||||
.bind(content_id)
|
||||
.fetch_optional(&mut *conn)
|
||||
.await?;
|
||||
let apply = current.as_ref().is_none_or(|row| {
|
||||
let current_hlc: i64 = row.get("hlc_ms");
|
||||
@@ -2235,8 +2260,9 @@ async fn apply_like_state(
|
||||
if !apply {
|
||||
return Ok(false);
|
||||
}
|
||||
let local_track_id = track_id_by_content_id(pool, &content_id).await?;
|
||||
let metadata = fed.cloned();
|
||||
let local_track_id = aliases
|
||||
.project(conn, user_id, liked, None, &iso_from_ms(hlc_ms))
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO furumusic__fed_state_like
|
||||
(user_id, content_id, liked, hlc_ms, op_id, local_track_id, fed_json)
|
||||
@@ -2249,37 +2275,14 @@ async fn apply_like_state(
|
||||
fed_json = COALESCE(EXCLUDED.fed_json, furumusic__fed_state_like.fed_json)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&content_id)
|
||||
.bind(content_id)
|
||||
.bind(liked)
|
||||
.bind(hlc_ms)
|
||||
.bind(op_id)
|
||||
.bind(local_track_id)
|
||||
.bind(metadata.map(serde_json::to_value).transpose()?)
|
||||
.execute(pool)
|
||||
.bind(fed.map(serde_json::to_value).transpose()?)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
if let Some(track_id) = local_track_id {
|
||||
if liked {
|
||||
let created_at = iso_from_ms(hlc_ms);
|
||||
sqlx::query(
|
||||
"INSERT INTO furumusic__user_liked_track (user_id, track_id, created_at)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (user_id, track_id) DO NOTHING",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(track_id)
|
||||
.bind(created_at)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
} else {
|
||||
sqlx::query(
|
||||
"DELETE FROM furumusic__user_liked_track WHERE user_id = $1 AND track_id = $2",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(track_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
use sqlx::{PgConnection, PgPool};
|
||||
|
||||
pub(crate) async fn lock(conn: &mut PgConnection, user: i64) -> sqlx::Result<()> {
|
||||
sqlx::query(
|
||||
"SELECT pg_advisory_xact_lock(hashtextextended('furumusic-like:' || $1::bigint::text,0))",
|
||||
)
|
||||
.bind(user)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) struct Aliases {
|
||||
ids: Vec<i64>,
|
||||
visible: Vec<i64>,
|
||||
}
|
||||
|
||||
impl Aliases {
|
||||
pub(super) async fn load(conn: &mut PgConnection, content: &str) -> sqlx::Result<Self> {
|
||||
let rows: Vec<(i64,bool)> = sqlx::query_as(
|
||||
"SELECT track_id, hidden FROM furumusic__track_content_alias WHERE content_id=$1 ORDER BY track_id"
|
||||
).bind(content).fetch_all(conn).await?;
|
||||
Ok(Self {
|
||||
ids: rows.iter().map(|r| r.0).collect(),
|
||||
visible: rows.into_iter().filter(|r| !r.1).map(|r| r.0).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn existing(
|
||||
&self,
|
||||
conn: &mut PgConnection,
|
||||
user: i64,
|
||||
) -> sqlx::Result<Option<i64>> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT track_id FROM furumusic__user_liked_track WHERE user_id=$1 AND track_id=ANY($2)
|
||||
ORDER BY (track_id=ANY($3)) DESC, id LIMIT 1",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(&self.ids)
|
||||
.bind(&self.visible)
|
||||
.fetch_optional(conn)
|
||||
.await
|
||||
}
|
||||
|
||||
// Only one local row represents a signed, content-addressed like. Preserve
|
||||
// the existing visible edition, including the one the local listener chose.
|
||||
pub(super) async fn project(
|
||||
&self,
|
||||
conn: &mut PgConnection,
|
||||
user: i64,
|
||||
liked: bool,
|
||||
preferred: Option<i64>,
|
||||
created_at: &str,
|
||||
) -> sqlx::Result<Option<i64>> {
|
||||
let existing = self.existing(conn, user).await?;
|
||||
let chosen = existing
|
||||
.filter(|id| self.visible.contains(id))
|
||||
.or_else(|| preferred.filter(|id| self.visible.contains(id)))
|
||||
.or_else(|| self.visible.first().copied());
|
||||
sqlx::query(
|
||||
"DELETE FROM furumusic__user_liked_track WHERE user_id=$1 AND track_id=ANY($2)
|
||||
AND track_id IS DISTINCT FROM $3",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(&self.ids)
|
||||
.bind(if liked { chosen } else { None })
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
if let Some(id) = chosen.filter(|_| liked) {
|
||||
sqlx::query(
|
||||
"INSERT INTO furumusic__user_liked_track(user_id,track_id,created_at) VALUES($1,$2,$3)
|
||||
ON CONFLICT(user_id,track_id) DO NOTHING"
|
||||
).bind(user).bind(id).bind(created_at).execute(conn).await?;
|
||||
}
|
||||
Ok(chosen)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn toggle(
|
||||
pool: &PgPool,
|
||||
user: i64,
|
||||
track: i64,
|
||||
) -> sqlx::Result<Option<(bool, Option<String>, Vec<i64>)>> {
|
||||
let mut tx = pool.begin().await?;
|
||||
lock(&mut tx, user).await?;
|
||||
let row: Option<(Option<String>,)> = sqlx::query_as(
|
||||
"SELECT a.content_id FROM furumusic__track t LEFT JOIN furumusic__track_content_alias a ON a.track_id=t.id
|
||||
WHERE t.id=$1"
|
||||
).bind(track).fetch_optional(&mut *tx).await?;
|
||||
let Some((content,)) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let aliases = match &content {
|
||||
Some(content) => Aliases::load(&mut tx, content).await?,
|
||||
None => Aliases {
|
||||
ids: vec![track],
|
||||
visible: vec![track],
|
||||
},
|
||||
};
|
||||
let pending: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM furumusic__fed_state_like
|
||||
WHERE user_id=$1 AND content_id=$2 AND liked AND local_track_id IS NULL)",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(content.as_deref())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let liked = !pending && aliases.existing(&mut tx, user).await?.is_none();
|
||||
if liked && aliases.visible.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
aliases
|
||||
.project(&mut tx, user, liked, Some(track), &super::now_iso())
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Some((liked, content, aliases.ids)))
|
||||
}
|
||||
|
||||
pub(crate) async fn on_content_available(
|
||||
conn: &mut PgConnection,
|
||||
content: &str,
|
||||
preferred: Option<i64>,
|
||||
) -> sqlx::Result<()> {
|
||||
let users = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT user_id FROM furumusic__fed_state_like WHERE content_id=$1
|
||||
UNION
|
||||
SELECT l.user_id FROM furumusic__track_content_alias a
|
||||
JOIN furumusic__user_liked_track l ON l.track_id=a.track_id
|
||||
WHERE a.content_id=$1 ORDER BY user_id",
|
||||
)
|
||||
.bind(content)
|
||||
.fetch_all(&mut *conn)
|
||||
.await?;
|
||||
if users.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for user in users {
|
||||
lock(conn, user).await?;
|
||||
let aliases = Aliases::load(conn, content).await?;
|
||||
let state: Option<(bool, i64)> = sqlx::query_as(
|
||||
"SELECT liked, hlc_ms FROM furumusic__fed_state_like WHERE user_id=$1 AND content_id=$2"
|
||||
).bind(user).bind(content).fetch_optional(&mut *conn).await?;
|
||||
if let Some((liked, ms)) = state {
|
||||
let chosen = aliases
|
||||
.project(conn, user, liked, preferred, &super::iso_from_ms(ms))
|
||||
.await?;
|
||||
sqlx::query("UPDATE furumusic__fed_state_like SET local_track_id=$3 WHERE user_id=$1 AND content_id=$2")
|
||||
.bind(user).bind(content).bind(chosen).execute(&mut *conn).await?;
|
||||
} else if aliases.existing(conn, user).await?.is_some() {
|
||||
aliases
|
||||
.project(conn, user, true, preferred, &super::now_iso())
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::federation::devices::{apply_like_state, record_track_like};
|
||||
|
||||
async fn local_rows(pool: &PgPool) -> sqlx::Result<Vec<i64>> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT track_id FROM furumusic__user_liked_track WHERE user_id=1 ORDER BY track_id",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
|
||||
async fn catalog_aliases_share_one_like_across_web_sync_and_import() -> anyhow::Result<()> {
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?)
|
||||
.await?;
|
||||
sqlx::raw_sql("
|
||||
CREATE TEMP TABLE furumusic__track(id bigint PRIMARY KEY,title text DEFAULT 'Taking Off',
|
||||
release_id bigint DEFAULT 1,audio_file_id bigint,is_hidden bool DEFAULT false,
|
||||
track_number int,disc_number int,duration_seconds float8 DEFAULT 220);
|
||||
CREATE TEMP TABLE furumusic__release(id bigint PRIMARY KEY,title text,year int,is_hidden bool DEFAULT false);
|
||||
CREATE TEMP TABLE furumusic__media_file(id bigint PRIMARY KEY,sha256_hash text);
|
||||
CREATE TEMP TABLE furumusic__federation_content_id_cache(media_file_id bigint PRIMARY KEY,sha256_hash text,content_id text,updated_at text);
|
||||
CREATE TEMP TABLE furumusic__track_artist(track_id bigint,artist_id bigint,role text,position int);
|
||||
CREATE TEMP TABLE furumusic__artist(id bigint,name text);
|
||||
CREATE TEMP TABLE furumusic__user_liked_track(id bigserial PRIMARY KEY,user_id bigint,track_id bigint,created_at text,UNIQUE(user_id,track_id));
|
||||
CREATE TEMP TABLE furumusic__fed_state_like(user_id bigint,content_id text,liked bool,hlc_ms bigint,op_id text,local_track_id bigint,fed_json jsonb,PRIMARY KEY(user_id,content_id));
|
||||
CREATE TEMP TABLE furumusic__fed_device_identity(user_id bigint,device_id text,group_id text,device_name text,local_seeded_at_ms bigint,local_seq bigint,last_hlc_ms bigint);
|
||||
CREATE TEMP TABLE furumusic__fed_sync_ops(user_id bigint,op_id text,origin_device_id text,seq bigint,kind text,payload_json jsonb,hlc_ms bigint,received_at_ms bigint,tombstone bool,UNIQUE(user_id,op_id));
|
||||
CREATE TEMP TABLE furumusic__fed_sync_vector(user_id bigint,device_id text,max_seq bigint,UNIQUE(user_id,device_id));
|
||||
INSERT INTO furumusic__fed_device_identity VALUES(1,'web','g','web',1,0,0);
|
||||
INSERT INTO furumusic__release(id,title) VALUES(1,'Ambitions');
|
||||
INSERT INTO furumusic__track(id,audio_file_id) VALUES(5672,1),(5686,2),(5797,3),(50,4);
|
||||
INSERT INTO furumusic__media_file VALUES(1,'one'),(2,'two'),(3,'three'),(4,'new');
|
||||
INSERT INTO furumusic__federation_content_id_cache(media_file_id,sha256_hash,content_id) VALUES
|
||||
(1,'one','b3:'||repeat('a',64)),(2,'two','b3:'||repeat('a',64)),
|
||||
(3,'three','b3:'||repeat('b',64)),(4,'stale','b3:'||repeat('a',64));
|
||||
").execute(&pool).await?;
|
||||
sqlx::raw_sql(&include_str!("track_content_alias.sql").replacen(
|
||||
"CREATE VIEW",
|
||||
"CREATE TEMP VIEW",
|
||||
1,
|
||||
))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
let content = format!("b3:{}", "a".repeat(64));
|
||||
let local = toggle(&pool, 1, 5686).await?.unwrap();
|
||||
assert_eq!(local, (true, Some(content.clone()), vec![5672, 5686]));
|
||||
record_track_like(&pool, 1, 5686, true).await?;
|
||||
assert_eq!(local_rows(&pool).await?, [5686]);
|
||||
assert!(toggle(&pool, 1, 5797).await?.unwrap().0);
|
||||
record_track_like(&pool, 1, 5797, true).await?;
|
||||
let uncached = toggle(&pool, 1, 50).await?.unwrap();
|
||||
assert_eq!(uncached, (true, None, vec![50]));
|
||||
let mut tx = pool.begin().await?;
|
||||
on_content_available(&mut tx, &content, Some(5672)).await?;
|
||||
tx.commit().await?;
|
||||
assert_eq!(local_rows(&pool).await?, [50, 5686, 5797]);
|
||||
assert!(!toggle(&pool, 1, 5672).await?.unwrap().0);
|
||||
record_track_like(&pool, 1, 5672, false).await?;
|
||||
record_track_like(&pool, 1, 5686, true).await?; // A delayed callback cannot restore it.
|
||||
assert_eq!(local_rows(&pool).await?, [50, 5797]);
|
||||
assert!(apply_like_state(&pool, 1, &content, true, None, i64::MAX - 1, "peer:1").await?);
|
||||
assert!(!apply_like_state(&pool, 1, &content, false, None, 1, "old").await?);
|
||||
assert_eq!(local_rows(&pool).await?, [50, 5672, 5797]);
|
||||
assert!(apply_like_state(&pool, 1, &content, false, None, i64::MAX, "peer:2").await?);
|
||||
assert_eq!(local_rows(&pool).await?, [50, 5797]);
|
||||
|
||||
// Restore the legacy double insert, including the user's original, higher track ID.
|
||||
sqlx::raw_sql(
|
||||
"INSERT INTO furumusic__user_liked_track(user_id,track_id,created_at)
|
||||
VALUES(1,5686,'first'),(1,5672,'second'),(2,5672,'other user')",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::raw_sql(include_str!("repair_like_aliases.sql"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert_eq!(local_rows(&pool).await?, [50, 5686, 5797]);
|
||||
let other: i64 =
|
||||
sqlx::query_scalar("SELECT track_id FROM furumusic__user_liked_track WHERE user_id=2")
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(other, 5672);
|
||||
sqlx::raw_sql(
|
||||
"INSERT INTO furumusic__media_file VALUES(5,'five');
|
||||
INSERT INTO furumusic__track(id,audio_file_id) VALUES(60,5)",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert!(toggle(&pool, 1, 60).await?.unwrap().0);
|
||||
let late_hash = format!("b3:{}", "c".repeat(64));
|
||||
crate::federation::persist_content_id(&pool, 4, "new", &late_hash).await?;
|
||||
crate::federation::persist_content_id(&pool, 5, "five", &late_hash).await?;
|
||||
assert_eq!(local_rows(&pool).await?, [50, 5686, 5797]);
|
||||
assert!(!toggle(&pool, 1, 60).await?.unwrap().0);
|
||||
assert_eq!(local_rows(&pool).await?, [5686, 5797]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
-- A local click inserted its selected track before device sync chose another
|
||||
-- copy of the same audio. Keep the first visible insertion for each listener.
|
||||
WITH ranked AS (
|
||||
SELECT l.id, row_number() OVER (
|
||||
PARTITION BY l.user_id, a.content_id ORDER BY a.hidden, l.id
|
||||
) AS position
|
||||
FROM furumusic__user_liked_track l
|
||||
JOIN furumusic__track_content_alias a ON a.track_id = l.track_id
|
||||
)
|
||||
DELETE FROM furumusic__user_liked_track l USING ranked
|
||||
WHERE l.id = ranked.id AND ranked.position > 1
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE VIEW furumusic__track_content_alias AS
|
||||
SELECT t.id AS track_id, c.content_id, (t.is_hidden OR r.is_hidden) AS hidden
|
||||
FROM furumusic__federation_content_id_cache c
|
||||
JOIN furumusic__media_file m ON m.id = c.media_file_id AND m.sha256_hash = c.sha256_hash
|
||||
JOIN furumusic__track t ON t.audio_file_id = m.id
|
||||
JOIN furumusic__release r ON r.id = t.release_id
|
||||
+10
-3
@@ -1331,21 +1331,28 @@ async fn persist_content_id(
|
||||
sha256_hash: &str,
|
||||
content_id: &str,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
let mut tx = pool.begin().await?;
|
||||
let written = sqlx::query(
|
||||
"INSERT INTO furumusic__federation_content_id_cache
|
||||
(media_file_id, sha256_hash, content_id, updated_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (media_file_id) DO UPDATE SET
|
||||
sha256_hash = EXCLUDED.sha256_hash,
|
||||
content_id = EXCLUDED.content_id,
|
||||
updated_at = EXCLUDED.updated_at",
|
||||
updated_at = EXCLUDED.updated_at
|
||||
WHERE (furumusic__federation_content_id_cache.sha256_hash, furumusic__federation_content_id_cache.content_id)
|
||||
IS DISTINCT FROM (EXCLUDED.sha256_hash, EXCLUDED.content_id)",
|
||||
)
|
||||
.bind(media_file_id)
|
||||
.bind(sha256_hash)
|
||||
.bind(content_id)
|
||||
.bind(now_iso())
|
||||
.execute(pool)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if written.rows_affected() > 0 {
|
||||
devices::likes::on_content_available(&mut tx, content_id, None).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -638,6 +638,7 @@ async fn materialize(
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
{
|
||||
super::devices::likes::on_content_available(&mut tx, content_id, Some(track_id)).await?;
|
||||
tx.commit().await?;
|
||||
return Ok(track_id);
|
||||
}
|
||||
@@ -731,14 +732,7 @@ async fn materialize(
|
||||
.bind(now_iso())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE furumusic__fed_state_like
|
||||
SET local_track_id = $2 WHERE content_id = $1",
|
||||
)
|
||||
.bind(content_id)
|
||||
.bind(track_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
super::devices::likes::on_content_available(&mut tx, content_id, Some(track_id)).await?;
|
||||
sqlx::query(
|
||||
"UPDATE furumusic__fed_state_playlist_item
|
||||
SET local_track_id = $2 WHERE content_id = $1",
|
||||
@@ -748,7 +742,7 @@ async fn materialize(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
super::devices::materialize_content_state(pool, content_id, track_id).await?;
|
||||
super::devices::materialize_playlist_items(pool, content_id, track_id).await?;
|
||||
|
||||
// Artwork is non-authoritative for identity and may be installed after
|
||||
// the audio transaction. Failure does not invalidate a verified track.
|
||||
|
||||
@@ -3021,7 +3021,48 @@ pub mod db_migrations {
|
||||
const OPERATIONS: &'static [Operation] = &[Operation::custom(add_playlist_artwork).build()];
|
||||
}
|
||||
|
||||
#[cot::db::migrations::migration_op]
|
||||
async fn repair_like_aliases(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
|
||||
ctx.db.raw(
|
||||
"CREATE INDEX idx_fed_like_content_user ON furumusic__fed_state_like(content_id,user_id)"
|
||||
).await?;
|
||||
ctx.db
|
||||
.raw(include_str!(
|
||||
"../federation/devices/track_content_alias.sql"
|
||||
))
|
||||
.await?;
|
||||
ctx.db
|
||||
.raw(include_str!(
|
||||
"../federation/devices/repair_like_aliases.sql"
|
||||
))
|
||||
.await?;
|
||||
ctx.db
|
||||
.raw(
|
||||
"UPDATE furumusic__fed_state_like f SET local_track_id=l.track_id
|
||||
FROM furumusic__user_liked_track l
|
||||
JOIN furumusic__track_content_alias a ON a.track_id=l.track_id
|
||||
WHERE f.user_id=l.user_id AND f.content_id=a.content_id AND f.liked
|
||||
AND NOT a.hidden AND f.local_track_id IS DISTINCT FROM l.track_id",
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct M0062RepairLikeAliases;
|
||||
impl migrations::Migration for M0062RepairLikeAliases {
|
||||
const APP_NAME: &'static str = "furumusic";
|
||||
const MIGRATION_NAME: &'static str = "m_0062_repair_like_aliases";
|
||||
const DEPENDENCIES: &'static [migrations::MigrationDependency] =
|
||||
&[migrations::MigrationDependency::migration(
|
||||
"furumusic",
|
||||
"m_0061_add_playlist_artwork",
|
||||
)];
|
||||
const OPERATIONS: &'static [Operation] = &[Operation::custom(repair_like_aliases).build()];
|
||||
}
|
||||
|
||||
pub const MIGRATIONS: &[&SyncDynMigration] = &[
|
||||
&M0062RepairLikeAliases,
|
||||
&M0061AddPlaylistArtwork,
|
||||
&M0060RepairLegacyWebListenDurations,
|
||||
&M0059AddSidebarPinOrder,
|
||||
|
||||
@@ -562,6 +562,8 @@ pub(super) struct PlayHistoryPage {
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub(super) struct LikeStatus {
|
||||
pub(super) liked: bool,
|
||||
pub(super) content_id: Option<String>,
|
||||
pub(super) affected_track_ids: Vec<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
WITH stored AS (
|
||||
SELECT track_id FROM furumusic__user_liked_track WHERE user_id = $1
|
||||
), recordings AS (
|
||||
SELECT a.content_id FROM stored s JOIN furumusic__track_content_alias a USING (track_id)
|
||||
UNION
|
||||
SELECT content_id FROM furumusic__fed_state_like
|
||||
WHERE user_id = $1 AND liked AND local_track_id IS NULL
|
||||
)
|
||||
SELECT track_id FROM stored
|
||||
UNION
|
||||
SELECT a.track_id FROM recordings r JOIN furumusic__track_content_alias a USING (content_id)
|
||||
WHERE NOT a.hidden
|
||||
+24
-103
@@ -34,6 +34,7 @@ mod listening;
|
||||
mod pins;
|
||||
mod playlist_artwork;
|
||||
mod playlist_image;
|
||||
mod release_likes;
|
||||
mod queries;
|
||||
mod rows;
|
||||
mod sharing;
|
||||
@@ -7915,38 +7916,20 @@ async fn toggle_like_track_handler(
|
||||
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
|
||||
};
|
||||
let track_id = path.0.track_id;
|
||||
let existing: Option<(i64,)> = sqlx::query_as(
|
||||
"SELECT id FROM furumusic__user_liked_track WHERE user_id = $1 AND track_id = $2",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(track_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
if existing.is_some() {
|
||||
sqlx::query("DELETE FROM furumusic__user_liked_track WHERE user_id = $1 AND track_id = $2")
|
||||
.bind(user.id)
|
||||
.bind(track_id)
|
||||
.execute(pool)
|
||||
let Some((liked, content_id, affected_track_ids)) =
|
||||
crate::federation::devices::likes::toggle(pool, user.id, track_id)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
record_fed_track_like(pool, user.id, track_id, false).await;
|
||||
Json(LikeStatus { liked: false }).into_response()
|
||||
} else {
|
||||
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO furumusic__user_liked_track (user_id, track_id, created_at) VALUES ($1, $2, $3)",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(track_id)
|
||||
.bind(&now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
record_fed_track_like(pool, user.id, track_id, true).await;
|
||||
Json(LikeStatus { liked: true }).into_response()
|
||||
}
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?
|
||||
else {
|
||||
return Ok(json_error(StatusCode::NOT_FOUND, "track not found"));
|
||||
};
|
||||
record_fed_track_like(pool, user.id, track_id, liked).await;
|
||||
Json(LikeStatus {
|
||||
liked,
|
||||
content_id,
|
||||
affected_track_ids,
|
||||
})
|
||||
.into_response()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -7963,70 +7946,13 @@ async fn like_release_handler(
|
||||
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
|
||||
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
|
||||
};
|
||||
let release_id = path.0.id;
|
||||
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
let track_ids = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT id FROM furumusic__track WHERE release_id = $1 AND is_hidden = false",
|
||||
)
|
||||
.bind(release_id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
// Check if ALL tracks in this release are already liked
|
||||
let total = track_ids.len() as i64;
|
||||
|
||||
let liked_count: (i64,) = sqlx::query_as(
|
||||
r#"SELECT COUNT(*) FROM furumusic__user_liked_track ult
|
||||
JOIN furumusic__track t ON t.id = ult.track_id
|
||||
WHERE ult.user_id = $1 AND t.release_id = $2 AND t.is_hidden = false"#,
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(release_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
if liked_count.0 >= total && total > 0 {
|
||||
// Unlike all tracks in release
|
||||
sqlx::query(
|
||||
r#"DELETE FROM furumusic__user_liked_track
|
||||
WHERE user_id = $1 AND track_id IN (
|
||||
SELECT id FROM furumusic__track WHERE release_id = $2 AND is_hidden = false
|
||||
)"#,
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(release_id)
|
||||
.execute(pool)
|
||||
let (liked, changed) = release_likes::toggle(pool, user.id, path.0.id)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
for track_id in &track_ids {
|
||||
record_fed_track_like(pool, user.id, *track_id, false).await;
|
||||
}
|
||||
Json(LikeStatus { liked: false }).into_response()
|
||||
} else {
|
||||
// Like all tracks in release (skip already liked)
|
||||
sqlx::query(
|
||||
r#"INSERT INTO furumusic__user_liked_track (user_id, track_id, created_at)
|
||||
SELECT $1, t.id, $3
|
||||
FROM furumusic__track t
|
||||
WHERE t.release_id = $2 AND t.is_hidden = false
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM furumusic__user_liked_track ult
|
||||
WHERE ult.user_id = $1 AND ult.track_id = t.id
|
||||
)"#,
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(release_id)
|
||||
.bind(&now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
for track_id in &track_ids {
|
||||
record_fed_track_like(pool, user.id, *track_id, true).await;
|
||||
}
|
||||
Json(LikeStatus { liked: true }).into_response()
|
||||
for track_id in changed {
|
||||
record_fed_track_like(pool, user.id, track_id, liked).await;
|
||||
}
|
||||
Json(serde_json::json!({ "liked": liked })).into_response()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -8042,17 +7968,12 @@ async fn liked_ids_handler(
|
||||
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
|
||||
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
|
||||
};
|
||||
let rows: Vec<(i64,)> =
|
||||
sqlx::query_as("SELECT track_id FROM furumusic__user_liked_track WHERE user_id = $1")
|
||||
.bind(user.id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
Json(LikedIds {
|
||||
track_ids: rows.into_iter().map(|r| r.0).collect(),
|
||||
})
|
||||
.into_response()
|
||||
let track_ids = sqlx::query_scalar(include_str!("liked_ids.sql"))
|
||||
.bind(user.id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
Json(LikedIds { track_ids }).into_response()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
use sqlx::PgPool;
|
||||
|
||||
pub(super) async fn toggle(
|
||||
pool: &PgPool,
|
||||
user: i64,
|
||||
release: i64,
|
||||
) -> anyhow::Result<(bool, Vec<i64>)> {
|
||||
let mut tx = pool.begin().await?;
|
||||
crate::federation::devices::likes::lock(&mut tx, user).await?;
|
||||
let recordings = sqlx::query_as::<_, (i64, Vec<i64>, bool)>(include_str!("release_likes.sql"))
|
||||
.bind(user)
|
||||
.bind(release)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let liked = recordings.is_empty()
|
||||
|| recordings
|
||||
.iter()
|
||||
.any(|(_, ids, remote)| ids.is_empty() && !remote);
|
||||
let changed: Vec<i64>;
|
||||
if liked {
|
||||
changed = recordings
|
||||
.into_iter()
|
||||
.filter(|(_, ids, remote)| ids.is_empty() && !remote)
|
||||
.map(|(id, _, _)| id)
|
||||
.collect();
|
||||
sqlx::query(
|
||||
"INSERT INTO furumusic__user_liked_track (user_id, track_id, created_at)
|
||||
SELECT $1, id, $3 FROM unnest($2::bigint[]) AS id
|
||||
ON CONFLICT (user_id, track_id) DO NOTHING",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(&changed)
|
||||
.bind(chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
} else {
|
||||
let stored: Vec<i64> = recordings
|
||||
.iter()
|
||||
.flat_map(|(_, ids, _)| ids.iter().copied())
|
||||
.collect();
|
||||
sqlx::query(
|
||||
"DELETE FROM furumusic__user_liked_track WHERE user_id=$1 AND track_id=ANY($2)",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(stored)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
changed = recordings.into_iter().map(|(id, _, _)| id).collect();
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok((liked, changed))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
|
||||
async fn release_likes_keep_one_copy_and_light_up_each_alias() -> anyhow::Result<()> {
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?)
|
||||
.await?;
|
||||
sqlx::raw_sql("
|
||||
CREATE TEMP TABLE furumusic__track(id bigint, release_id bigint, is_hidden boolean DEFAULT false);
|
||||
CREATE TEMP TABLE furumusic__track_content_alias(track_id bigint, content_id text, hidden boolean DEFAULT false);
|
||||
CREATE TEMP TABLE furumusic__user_liked_track(user_id bigint, track_id bigint, created_at text,
|
||||
PRIMARY KEY(user_id, track_id));
|
||||
CREATE TEMP TABLE furumusic__fed_state_like(user_id bigint, content_id text, liked boolean, local_track_id bigint);
|
||||
INSERT INTO furumusic__track(id, release_id) VALUES (1,10),(2,10),(3,10),(4,10),(5,20),(6,30),(7,40);
|
||||
INSERT INTO furumusic__track_content_alias(track_id, content_id)
|
||||
VALUES (1,'album'),(2,'album'),(3,'third'),(5,'album'),(6,'single'),(7,'pending');
|
||||
INSERT INTO furumusic__user_liked_track VALUES (9,5,'original'),(9,6,'single'),(10,1,'other user');
|
||||
INSERT INTO furumusic__fed_state_like VALUES (9,'pending',true,NULL);
|
||||
").execute(&pool).await?;
|
||||
|
||||
let (liked, mut added) = toggle(&pool, 9, 10).await?;
|
||||
added.sort_unstable();
|
||||
assert!(liked);
|
||||
assert_eq!(added, [3, 4]); // Preserve the original copy from release 20.
|
||||
let mut ids = sqlx::query_scalar::<_, i64>(include_str!("liked_ids.sql"))
|
||||
.bind(9_i64)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
ids.sort_unstable();
|
||||
assert_eq!(ids, [1, 2, 3, 4, 5, 6, 7]);
|
||||
let (liked, mut removed) = toggle(&pool, 9, 10).await?;
|
||||
removed.sort_unstable();
|
||||
assert!(!liked);
|
||||
assert_eq!(removed, [1, 3, 4]);
|
||||
let stored: Vec<(i64, i64)> = sqlx::query_as(
|
||||
"SELECT user_id, track_id FROM furumusic__user_liked_track ORDER BY user_id, track_id",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
assert_eq!(stored, [(9, 6), (10, 1)]);
|
||||
assert_eq!(toggle(&pool, 9, 40).await?, (false, vec![7]));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
-- One candidate per recording. An unindexed track keeps its catalog identity.
|
||||
WITH members AS (
|
||||
SELECT DISTINCT ON (a.content_id, CASE WHEN a.content_id IS NULL THEN t.id END)
|
||||
t.id AS track_id, a.content_id
|
||||
FROM furumusic__track t
|
||||
LEFT JOIN furumusic__track_content_alias a ON a.track_id = t.id
|
||||
WHERE t.release_id = $2 AND NOT t.is_hidden
|
||||
ORDER BY a.content_id, CASE WHEN a.content_id IS NULL THEN t.id END, t.id
|
||||
), copies AS (
|
||||
SELECT m.track_id, m.content_id, ARRAY(
|
||||
SELECT m.track_id
|
||||
UNION ALL
|
||||
SELECT a.track_id FROM furumusic__track_content_alias a
|
||||
WHERE a.content_id = m.content_id AND a.track_id <> m.track_id
|
||||
) AS aliases FROM members m
|
||||
)
|
||||
SELECT c.track_id, ARRAY(
|
||||
SELECT l.track_id FROM furumusic__user_liked_track l
|
||||
WHERE l.user_id = $1 AND l.track_id = ANY(c.aliases)
|
||||
) AS liked_ids,
|
||||
EXISTS (
|
||||
SELECT 1 FROM furumusic__fed_state_like f
|
||||
WHERE f.user_id = $1 AND f.content_id = c.content_id
|
||||
AND f.liked AND f.local_track_id IS NULL
|
||||
) AS liked_remotely
|
||||
FROM copies c
|
||||
@@ -4,7 +4,6 @@
|
||||
get tiles() { return $store.playlistHeader.urls },
|
||||
get editing() { return $store.playlists.isEditingCurrent() },
|
||||
get target() { return $store.pins.target('playlist', this.playlist) }}"
|
||||
:class="{'cover-editor-open': editing && header.pickerOpen}"
|
||||
@keydown.escape="if (editing && !header.busy) {
|
||||
$event.stopPropagation();
|
||||
if (header.pickerOpen) { header.pickerOpen = false; $refs.coverToggle.focus() }
|
||||
@@ -22,7 +21,7 @@
|
||||
<button type="button" class="playlist-cover-toggle" x-ref="coverToggle" x-show="editing" x-cloak
|
||||
aria-label="{{ t.player_edit_playlist_cover }}" title="{{ t.player_edit_playlist_cover }}"
|
||||
:disabled="header.busy" aria-controls="playlist-cover-editor" :aria-expanded="header.pickerOpen"
|
||||
@click="header.pickerOpen = !header.pickerOpen; if (header.pickerOpen) $nextTick(() => $refs.coverEditor.querySelector('[aria-pressed=true]')?.focus({preventScroll:true}))">
|
||||
@click="header.togglePicker($el, $refs.coverEditor)">
|
||||
<span><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="m14 6 4 4M4 20l4.5-1 11-11a2.8 2.8 0 0 0-4-4l-11 11z"/>
|
||||
</svg></span>
|
||||
@@ -63,7 +62,11 @@
|
||||
{% if !guest %}
|
||||
<div class="playlist-heading-pin" x-show="target">{% include "player/pin_button.html" %}</div>
|
||||
<fieldset class="playlist-cover-editor" id="playlist-cover-editor" x-ref="coverEditor"
|
||||
x-show="editing && header.pickerOpen" x-cloak :disabled="header.busy" aria-label="{{ t.player_playlist_cover }}">
|
||||
x-show="editing && header.pickerOpen" x-cloak :disabled="header.busy" aria-label="{{ t.player_playlist_cover }}"
|
||||
@pointerdown.window.capture="if (header.pickerOpen && !$el.contains($event.target) && !$refs.coverToggle.contains($event.target)) header.pickerOpen = false"
|
||||
@focusin.window="if (header.pickerOpen && !$el.contains($event.target) && !$refs.coverToggle.contains($event.target)) header.pickerOpen = false"
|
||||
@scroll.window.capture="if (header.pickerOpen && !$el.contains($event.target)) header.dismissScrolledPicker($refs.coverToggle)"
|
||||
@resize.window="if (header.pickerOpen) header.placePicker($refs.coverToggle, $el)">
|
||||
<div class="playlist-cover-modes" role="group" aria-label="{{ t.player_playlist_cover }}">
|
||||
<button type="button" class="playlist-cover-mode" data-mode="auto" :aria-pressed="header.mode === 'auto'" @click="header.setMode('auto')">{{ t.player_playlist_cover_auto }}</button>
|
||||
<button type="button" class="playlist-cover-mode" data-mode="releases" :aria-pressed="header.mode === 'releases'" @click="header.setMode('releases')">{{ t.player_playlist_cover_releases }}</button>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script>
|
||||
document.addEventListener('alpine:init', () => {
|
||||
let generation = 0;
|
||||
let pickerAnchorTop = 0;
|
||||
const savedMode = pl => pl?.cover_mode || 'auto';
|
||||
function automatic(pl) {
|
||||
if (pl?.auto_cover_urls?.length) return pl.auto_cover_urls;
|
||||
@@ -66,6 +67,33 @@ document.addEventListener('alpine:init', () => {
|
||||
cancel() {
|
||||
if (!this.busy) Alpine.store('playlists').stopEdit();
|
||||
},
|
||||
togglePicker(anchor, panel) {
|
||||
if (this.pickerOpen) {
|
||||
this.pickerOpen = false;
|
||||
return;
|
||||
}
|
||||
this.placePicker(anchor, panel);
|
||||
this.pickerOpen = true;
|
||||
Alpine.nextTick(() => {
|
||||
if (this.pickerOpen) panel.querySelector('[aria-pressed=true]')?.focus({preventScroll:true});
|
||||
});
|
||||
},
|
||||
placePicker(anchor, panel) {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
pickerAnchorTop = rect.top;
|
||||
const height = document.documentElement.clientHeight;
|
||||
const below = height - rect.bottom;
|
||||
const above = below < 250 && rect.top > below;
|
||||
const gap = 6;
|
||||
panel.style.setProperty('--anchor-left', rect.left + 'px');
|
||||
panel.style.top = above ? 'auto' : rect.bottom + gap + 'px';
|
||||
panel.style.bottom = above ? height - rect.top + gap + 'px' : 'auto';
|
||||
panel.style.maxHeight = Math.max(0, (above ? rect.top : below) - gap - 8) + 'px';
|
||||
},
|
||||
dismissScrolledPicker(anchor) {
|
||||
// A scroll that brought the trigger into view can be dispatched after its click.
|
||||
if (anchor.getBoundingClientRect().top !== pickerAnchorTop) this.pickerOpen = false;
|
||||
},
|
||||
setMode(mode) {
|
||||
if (this.busy) return;
|
||||
this.mode = mode;
|
||||
|
||||
@@ -2557,6 +2557,7 @@ document.addEventListener('alpine:init', () => {
|
||||
currentArtist: null,
|
||||
currentRelease: null,
|
||||
currentPlaylist: null,
|
||||
_playlistReadVersion: 0,
|
||||
_observer: null,
|
||||
searchQuery: '',
|
||||
searchResults: null,
|
||||
@@ -3474,26 +3475,51 @@ document.addEventListener('alpine:init', () => {
|
||||
async openPlaylist(id, options = {}) {
|
||||
if (GUEST) return;
|
||||
this._beginNavigation('#playlist/' + id, options);
|
||||
const version = this._navigationVersion;
|
||||
this.view = 'playlist_detail';
|
||||
this.currentPlaylist = null;
|
||||
return this._loadPlaylist(id, options);
|
||||
},
|
||||
|
||||
refreshLikedPlaylist() {
|
||||
if (this.view === 'playlist_detail' && this._activeHash === '#playlist/-1') {
|
||||
return this._loadPlaylist(-1);
|
||||
}
|
||||
},
|
||||
|
||||
reloadLikes() {
|
||||
return Promise.all([
|
||||
Alpine.store('likes').reload(), this.loadFederationLikes(),
|
||||
Alpine.store('playlists').reload(), this.refreshLikedPlaylist(),
|
||||
]);
|
||||
},
|
||||
|
||||
async _loadPlaylist(id, navigation) {
|
||||
const version = ++this._playlistReadVersion;
|
||||
const route = this._navigationVersion;
|
||||
const current = () => version === this._playlistReadVersion && route === this._navigationVersion;
|
||||
const likes = Number(id) === -1;
|
||||
try {
|
||||
const pending = Alpine.store('playlists')?.trackChange;
|
||||
if (pending?.id === Number(id)) {
|
||||
await pending.done;
|
||||
if (version !== this._navigationVersion) return;
|
||||
if (!current()) return;
|
||||
}
|
||||
const res = await fetch(`/api/player/playlists/${id}`);
|
||||
if (!res.ok) throw new Error('failed');
|
||||
const playlist = await res.json();
|
||||
if (version !== this._navigationVersion) return;
|
||||
if (Number(id) === -1) playlist.tracks = this.sortLikeTracks(playlist.tracks || []);
|
||||
if (!current()) return;
|
||||
const locals = playlist.tracks || [];
|
||||
if (likes) {
|
||||
// Keep already-visible remote likes until their endpoint finishes refreshing.
|
||||
const previous = navigation ? [] : this.currentPlaylist?.tracks.filter(t => t.federation_pending) || [];
|
||||
playlist.tracks = this.sortLikeTracks([...locals, ...previous]);
|
||||
}
|
||||
this.currentPlaylist = playlist;
|
||||
this._afterNavigation(options);
|
||||
if (navigation) this._afterNavigation(navigation);
|
||||
const federationResponse = await fetch(`/api/player/playlists/${id}/federation-tracks`);
|
||||
if (federationResponse.ok) {
|
||||
const references = await federationResponse.json();
|
||||
if (version !== this._navigationVersion) return;
|
||||
if (!current()) return;
|
||||
const federated = (references || [])
|
||||
.map(reference => {
|
||||
const track = this.federationTrackFromWire(reference.federation);
|
||||
@@ -3504,13 +3530,14 @@ document.addEventListener('alpine:init', () => {
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
if (federated.length) {
|
||||
const tracks = [...this.currentPlaylist.tracks, ...federated];
|
||||
this.currentPlaylist.tracks = Number(id) === -1 ? this.sortLikeTracks(tracks) : tracks;
|
||||
if (likes) {
|
||||
this.currentPlaylist.tracks = this.sortLikeTracks([...locals, ...federated]);
|
||||
} else if (federated.length) {
|
||||
this.currentPlaylist.tracks = [...this.currentPlaylist.tracks, ...federated];
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (version === this._navigationVersion && !this.currentPlaylist) this._afterNavigation(options);
|
||||
if (current() && navigation && !this.currentPlaylist) this._afterNavigation(navigation);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -4183,7 +4210,7 @@ document.addEventListener('alpine:init', () => {
|
||||
return this.setFederationLike(track, liked);
|
||||
},
|
||||
|
||||
async setFederationLike(track, liked) {
|
||||
async setFederationLike(track, liked, refresh = true) {
|
||||
const contentId = track?.key?.content_id;
|
||||
if (!contentId) return;
|
||||
const response = await fetch('/api/player/tracks/content/like', {
|
||||
@@ -4196,31 +4223,37 @@ document.addEventListener('alpine:init', () => {
|
||||
}),
|
||||
});
|
||||
if (!response.ok) return;
|
||||
if (liked) this.federationLiked.push(contentId);
|
||||
else this.federationLiked = this.federationLiked.filter(id => id !== contentId);
|
||||
if (this.currentPlaylist?.id === -1) {
|
||||
if (liked && !this.currentPlaylist.tracks.some(item => item.content_id === contentId)) {
|
||||
this.currentPlaylist = {
|
||||
...this.currentPlaylist,
|
||||
tracks: this.sortLikeTracks([
|
||||
...this.currentPlaylist.tracks,
|
||||
{
|
||||
...this.federationQueueTrack(track),
|
||||
sort_key: Date.now(),
|
||||
},
|
||||
]),
|
||||
};
|
||||
} else if (!liked) {
|
||||
this.currentPlaylist = {
|
||||
...this.currentPlaylist,
|
||||
tracks: this.currentPlaylist.tracks.filter(item => item.content_id !== contentId),
|
||||
};
|
||||
}
|
||||
this.updateLikeStatus(contentId, liked, []);
|
||||
if (refresh) await this.reloadLikes();
|
||||
},
|
||||
|
||||
updateLikeStatus(contentId, liked, trackIds) {
|
||||
if (contentId) {
|
||||
if (!liked) this.federationLiked = this.federationLiked.filter(id => id !== contentId);
|
||||
else if (!this.federationLiked.includes(contentId)) this.federationLiked.push(contentId);
|
||||
}
|
||||
if (!liked && this.currentPlaylist?.id === -1) {
|
||||
this.currentPlaylist.tracks = this.currentPlaylist.tracks.filter(track =>
|
||||
!(contentId && track.content_id === contentId) && !trackIds.includes(track.id));
|
||||
}
|
||||
},
|
||||
|
||||
uniqueLikeTracks(tracks) {
|
||||
const contentById = new Map();
|
||||
for (const track of tracks) {
|
||||
if (track.content_id) contentById.set(track.id, track.content_id);
|
||||
}
|
||||
const unique = new Map();
|
||||
for (const track of tracks) {
|
||||
const key = track.content_id || contentById.get(track.id) || track.id;
|
||||
const previous = unique.get(key);
|
||||
if (!previous || (previous.federation_pending && !track.federation_pending)) unique.set(key, track);
|
||||
}
|
||||
return [...unique.values()];
|
||||
},
|
||||
|
||||
sortLikeTracks(tracks) {
|
||||
return [...(tracks || [])].sort((left, right) => {
|
||||
return this.uniqueLikeTracks(tracks).sort((left, right) => {
|
||||
const order = Number(right.sort_key || 0) - Number(left.sort_key || 0);
|
||||
if (order) return order;
|
||||
const stable = String(left.content_id || left.id || '')
|
||||
@@ -4247,19 +4280,22 @@ document.addEventListener('alpine:init', () => {
|
||||
async toggleMixedReleaseLike(release) {
|
||||
const tracks = release?.tracks || [];
|
||||
if (!tracks.length) return;
|
||||
if (release.id && tracks.every(track => !track.federation_pending)) {
|
||||
return Alpine.store('likes').toggleRelease(release.id);
|
||||
}
|
||||
const liked = !this.isMixedReleaseLiked(release);
|
||||
const operations = [];
|
||||
for (const track of tracks) {
|
||||
for (const track of this.uniqueLikeTracks(tracks)) {
|
||||
if (track.federation_pending) {
|
||||
if (this.federationIsLiked(track._federationTrack) !== liked) {
|
||||
operations.push(this.setFederationLike(track._federationTrack, liked));
|
||||
operations.push(this.setFederationLike(track._federationTrack, liked, false));
|
||||
}
|
||||
} else if (Alpine.store('likes').has(track.id) !== liked) {
|
||||
operations.push(Alpine.store('likes').toggle(track.id));
|
||||
operations.push(Alpine.store('likes').toggle(track.id, false));
|
||||
}
|
||||
}
|
||||
await Promise.allSettled(operations);
|
||||
Alpine.store('playlists').reload();
|
||||
await this.reloadLikes();
|
||||
},
|
||||
|
||||
async playFederatedTrack(track, options = {}) {
|
||||
@@ -4566,9 +4602,9 @@ document.addEventListener('alpine:init', () => {
|
||||
return this._set.has(trackId);
|
||||
},
|
||||
|
||||
async toggle(trackId) {
|
||||
// Optimistic update
|
||||
if (this._set.has(trackId)) {
|
||||
async toggle(trackId, refresh = true) {
|
||||
const wasLiked = this._set.has(trackId);
|
||||
if (wasLiked) {
|
||||
this._set.delete(trackId);
|
||||
} else {
|
||||
this._set.add(trackId);
|
||||
@@ -4577,30 +4613,30 @@ document.addEventListener('alpine:init', () => {
|
||||
this._set = new Set(this._set);
|
||||
try {
|
||||
const res = await fetch(`/api/player/likes/toggle/${trackId}`, { method: 'POST' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data.liked) {
|
||||
this._set.add(trackId);
|
||||
} else {
|
||||
this._set.delete(trackId);
|
||||
}
|
||||
this._set = new Set(this._set);
|
||||
Alpine.store('playlists').reload();
|
||||
if (!res.ok) throw new Error('like update failed');
|
||||
const data = await res.json();
|
||||
const ids = data.affected_track_ids?.length ? data.affected_track_ids : [trackId];
|
||||
for (const id of ids) {
|
||||
if (data.liked) this._set.add(id);
|
||||
else this._set.delete(id);
|
||||
}
|
||||
} catch {}
|
||||
this._set = new Set(this._set);
|
||||
const library = Alpine.store('library');
|
||||
library.updateLikeStatus(data.content_id, data.liked, ids);
|
||||
if (refresh) await Promise.all([Alpine.store('playlists').reload(), library.refreshLikedPlaylist()]);
|
||||
} catch {
|
||||
if (wasLiked) this._set.add(trackId);
|
||||
else this._set.delete(trackId);
|
||||
this._set = new Set(this._set);
|
||||
await this.reload();
|
||||
}
|
||||
},
|
||||
|
||||
async toggleRelease(releaseId) {
|
||||
try {
|
||||
const res = await fetch(`/api/player/likes/release/${releaseId}`, { method: 'POST' });
|
||||
if (res.ok) {
|
||||
// Reload liked IDs
|
||||
const likesRes = await fetch('/api/player/likes');
|
||||
if (likesRes.ok) {
|
||||
const d = await likesRes.json();
|
||||
this._set = new Set(d.track_ids || []);
|
||||
}
|
||||
Alpine.store('playlists').reload();
|
||||
await Alpine.store('library').reloadLikes();
|
||||
}
|
||||
} catch {}
|
||||
},
|
||||
|
||||
@@ -896,7 +896,8 @@
|
||||
<span></span>
|
||||
<span style="text-align:right">{{ t.player_duration }}</span>
|
||||
</div>
|
||||
<template x-for="(track, idx) in $store.library.currentPlaylist.tracks" :key="track.playlist_track_id || (track.id + '-' + idx)">
|
||||
<template x-for="(track, idx) in $store.library.currentPlaylist.tracks"
|
||||
:key="$store.library.currentPlaylist.kind === 'likes' ? (track.content_id || track.id) : (track.playlist_track_id || (track.id + '-' + idx))">
|
||||
<div class="track-row playlist-track-row"
|
||||
:data-playlist-index="idx"
|
||||
:class="{ playing: $store.player.currentTrack && $store.player.currentTrack.id === track.id, editing: $store.playlists.isEditingCurrent(), dragging: $store.playlists._dragIdx === idx }"
|
||||
|
||||
@@ -541,11 +541,6 @@ button.user-stat:hover {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.playlist-detail-heading.cover-editor-open {
|
||||
grid-template-areas: "cover details pin" "cover editor editor";
|
||||
}
|
||||
.playlist-detail-heading.cover-editor-open .playlist-heading-cover { align-self: start; }
|
||||
|
||||
.playlist-heading-cover {
|
||||
grid-area: cover;
|
||||
position: relative;
|
||||
@@ -599,14 +594,21 @@ button.user-stat:hover {
|
||||
.playlist-detail-heading .playlist-cover-toggle:focus-visible, .playlist-cover-choice:focus-visible { outline-offset: -2px; }
|
||||
|
||||
.playlist-cover-editor {
|
||||
grid-area: editor;
|
||||
width: min(100%, 510px);
|
||||
--picker-width: min(336px, calc(100vw - 16px));
|
||||
position: fixed;
|
||||
z-index: 200;
|
||||
left: clamp(8px, var(--anchor-left), calc(100vw - var(--picker-width) - 8px));
|
||||
width: var(--picker-width);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-elevated);
|
||||
box-shadow: 0 8px 26px #0008;
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.playlist-cover-modes { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.playlist-cover-mode, .playlist-cover-file { border: 1px solid var(--bg-active); border-radius: 5px; padding: 6px 9px; color: var(--text-secondary); background: transparent; font: inherit; font-size: 13px; cursor: pointer; }
|
||||
@@ -6558,9 +6560,6 @@ button.user-stat:hover {
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.playlist-detail-heading.cover-editor-open {
|
||||
grid-template-areas: "cover details pin" "editor editor editor";
|
||||
}
|
||||
|
||||
.playlist-track-row.editing {
|
||||
grid-template-columns: 30px minmax(0, 1fr) auto;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// Render with FURU_PODCAST_RENDER_FIXTURE=1 cargo test renders_podcast_navigation_and_views.
|
||||
const assert = require('node:assert/strict');
|
||||
const {readFileSync} = require('node:fs');
|
||||
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
|
||||
const html = readFileSync('target/podcast-player-fixture.html', 'utf8');
|
||||
const alpine = readFileSync('target/podcast-alpine.min.js', 'utf8');
|
||||
const song = (id, content_id, sort_key) => ({
|
||||
id, content_id, sort_key, title:'Taking Off', duration_seconds:219,
|
||||
artists:[{id:1,name:'ONE OK ROCK'}], stream_url:'/api/player/stream/'+id,
|
||||
});
|
||||
const original = song(5672, 'b3:'+'a'.repeat(64), 30);
|
||||
const alias = {...original,id:5686};
|
||||
const other = song(5797, 'b3:'+'b'.repeat(64), 20);
|
||||
const remote = song(null, 'b3:'+'c'.repeat(64), 10);
|
||||
const reference = track => ({
|
||||
position:track.sort_key, content_id:track.content_id,
|
||||
federation:{content_id:track.content_id, title:track.title, artist_names:['ONE OK ROCK'],
|
||||
owner:'peer', item_id:track.content_id, duration_seconds:219},
|
||||
});
|
||||
|
||||
async function check(browser) {
|
||||
const page = await browser.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', err => errors.push(err.message));
|
||||
let liked = true, delay = false, releaseResponse;
|
||||
const writes = [];
|
||||
await page.route('**/*', async route => {
|
||||
const {hostname, pathname} = new URL(route.request().url());
|
||||
if (hostname === 'likes.test' && pathname === '/') return route.fulfill({contentType:'text/html',body:html});
|
||||
if (hostname === 'cdn.jsdelivr.net' && pathname.includes('alpine')) return route.fulfill({contentType:'application/javascript',body:alpine});
|
||||
const markers = liked ? [original,alias,other] : [other];
|
||||
const locals = liked && writes.includes(alias.id) ? [alias,other] : markers;
|
||||
if (pathname === '/api/player/playlists/-1/federation-tracks') {
|
||||
const rows = (liked ? [original,remote] : [remote]).map(reference);
|
||||
if (delay) {
|
||||
delay = false;
|
||||
await new Promise(resolve => {releaseResponse = resolve;});
|
||||
}
|
||||
return route.fulfill({json:rows});
|
||||
}
|
||||
if (pathname.startsWith('/api/player/likes/toggle/')) {
|
||||
writes.push(Number(pathname.split('/').at(-1)));
|
||||
liked = !liked;
|
||||
return route.fulfill({json:{liked,content_id:original.content_id,affected_track_ids:[original.id,alias.id]}});
|
||||
}
|
||||
const json = {
|
||||
'/api/player/playlists/-1':{id:-1,kind:'likes',title:'Likes',tracks:locals},
|
||||
'/api/player/playlists':[{id:-1,kind:'likes',track_count:liked ? 3 : 2}],
|
||||
'/api/player/likes':{track_ids:markers.map(t => t.id)},
|
||||
'/api/player/releases/7':{id:7,title:'Ambitions',artists:original.artists,uploaders:[],tracks:[original,alias,other]},
|
||||
'/api/player/tracks/content/like':(liked ? [original,other,remote] : [other,remote]).map(t => t.content_id),
|
||||
'/api/player/artists':{items:[],total:0,has_more:false},
|
||||
'/api/player/me':{id:1,name:'Listener'},
|
||||
};
|
||||
return route.fulfill({json:json[pathname] || []});
|
||||
});
|
||||
const rows = page.locator('.playlist-track-row');
|
||||
const waitForIds = ids => page.waitForFunction(expected => {
|
||||
const visible = Alpine.store('library').currentPlaylist?.tracks.map(t => t.id) || [];
|
||||
return JSON.stringify(visible) === JSON.stringify(expected);
|
||||
}, ids);
|
||||
await page.goto('http://likes.test/#playlist/-1');
|
||||
const remoteId = 'fed:'+remote.content_id;
|
||||
await waitForIds([original.id,other.id,remoteId]);
|
||||
assert.equal(await rows.count(), 3);
|
||||
await page.evaluate(() => {
|
||||
Alpine.store('queue').playRelease = (tracks, index) => { window.chosen = tracks[index]; };
|
||||
});
|
||||
await rows.nth(1).dblclick();
|
||||
assert.equal(await page.evaluate(() => window.chosen.id), other.id);
|
||||
await page.goto('http://likes.test/#artists');
|
||||
await page.waitForFunction(() => Alpine.store('library').view === 'artists');
|
||||
delay = true;
|
||||
const pending = page.waitForRequest(req => req.url().endsWith('/-1/federation-tracks'));
|
||||
await page.goto('http://likes.test/#playlist/-1');
|
||||
await pending;
|
||||
await rows.first().locator('.like-btn').click();
|
||||
await waitForIds([other.id,remoteId]);
|
||||
assert.deepEqual(writes,[original.id]);
|
||||
const oldResponse = page.waitForResponse(res => res.url().endsWith('/-1/federation-tracks'));
|
||||
releaseResponse();
|
||||
await (await oldResponse).finished();
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
await waitForIds([other.id,remoteId]);
|
||||
assert.deepEqual(await page.evaluate(([id,alias,other,content]) => {
|
||||
const likes = Alpine.store('likes');
|
||||
return [likes.has(id),likes.has(alias),likes.has(other),Alpine.store('library').federationLiked.includes(content)];
|
||||
},[original.id,alias.id,other.id,original.content_id]), [false,false,true,false]);
|
||||
await page.reload();
|
||||
await waitForIds([other.id,remoteId]);
|
||||
await page.goto('http://likes.test/#release/7');
|
||||
const releaseHeart = id => page.locator('[data-shared-track-id="'+id+'"] .like-btn');
|
||||
await releaseHeart(alias.id).click();
|
||||
await page.waitForFunction(id => Alpine.store('likes').has(id), original.id);
|
||||
for (const track of [original,alias,other]) assert.ok(await releaseHeart(track.id).evaluate(el => el.classList.contains('liked')));
|
||||
await page.goto('http://likes.test/#playlist/-1');
|
||||
await waitForIds([alias.id,other.id,remoteId]);
|
||||
assert.deepEqual(writes,[original.id,alias.id]);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless:true, ...(process.env.CHROME_PATH ? {executablePath:process.env.CHROME_PATH} : {}),
|
||||
});
|
||||
try {
|
||||
await check(browser);
|
||||
console.log('Liked song identities, source merging, playback and removal passed.');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(err => { console.error(err); process.exitCode = 1; });
|
||||
@@ -120,8 +120,23 @@ async function checkHeader(browser, width) {
|
||||
return {italic:s.fontStyle === 'italic',underline:rgb && +rgb[2] > +rgb[1] && +rgb[2] > +rgb[3]};
|
||||
});
|
||||
assert.ok(decoration.italic && decoration.underline,'editable title is italic with a green underline');
|
||||
const headerLayout = () => heading.evaluate(el => {
|
||||
const row = document.querySelector('.playlist-track-row');
|
||||
return [el.getBoundingClientRect().height, row.getBoundingClientRect().top, row.closest('.main-content').scrollHeight];
|
||||
});
|
||||
const initialLayout = await headerLayout();
|
||||
await showCoverEditor();
|
||||
assert.deepEqual(await headerLayout(), initialLayout, 'opening the artwork picker leaves the track list in place');
|
||||
await chooseMode('releases');
|
||||
assert.deepEqual(await headerLayout(), initialLayout, 'showing thumbnails keeps the header and page height stable');
|
||||
const popup = await editor.boundingBox(), anchor = await cover.boundingBox();
|
||||
assert.ok(popup.x >= 0 && popup.x + popup.width <= width + 1);
|
||||
assert.ok(Math.abs(popup.y - anchor.y - anchor.height) < 12 ||
|
||||
Math.abs(anchor.y - popup.y - popup.height) < 12, 'the picker floats next to the artwork');
|
||||
await activate(input);
|
||||
await editor.waitFor({state:'hidden'});
|
||||
assert.equal(await input.inputValue(), 'Draft that will be discarded', 'outside click preserves the header draft');
|
||||
await showCoverEditor();
|
||||
await page.keyboard.press('Escape');
|
||||
await editor.waitFor({state:'hidden'});
|
||||
assert.ok(await input.isVisible(),'closing the cover picker keeps the title draft');
|
||||
@@ -198,6 +213,8 @@ async function checkHeader(browser, width) {
|
||||
await chooseMode('releases');
|
||||
await activate(choices.nth(4));
|
||||
await activate(choices.nth(1));
|
||||
await page.keyboard.press('Escape');
|
||||
await editor.waitFor({state:'hidden'});
|
||||
const rows = page.locator('.playlist-track-row');
|
||||
let finishDelete;
|
||||
delayedDelete = new Promise(resolve => {finishDelete = resolve;});
|
||||
@@ -210,6 +227,7 @@ async function checkHeader(browser, width) {
|
||||
finishDelete();
|
||||
delayedDelete = null;
|
||||
await verifyArt([covers[1].cover_url]);
|
||||
await showCoverEditor();
|
||||
assert.equal(await choices.count(),4,'deleted track artwork is no longer offered');
|
||||
assert.equal(await editor.locator('.playlist-cover-choice[aria-pressed="true"]').count(),1);
|
||||
assert.equal(await input.inputValue(),draftTitle);
|
||||
|
||||
Reference in new issue
Block a user