diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3b00882 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +target +.git +.idea +.env +discover/node_modules +discover/dist diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8b97e2f --- /dev/null +++ b/.env.example @@ -0,0 +1,25 @@ +# Settings for compose.yaml. Copy this file to .env and fill it in. + +# Your Subsonic (e.g. Navidrome) server's API. For a server running on the Docker host, use +# http://host.docker.internal:4533/rest +SUBSONIC_BASE=http://host.docker.internal:4533/rest +SUBSONIC_USERNAME= +SUBSONIC_PASSWORD= + +# Password for playlistd's own database. Use letters and digits only, as it's put in a URL. +POSTGRES_PASSWORD= + +# Optional: your Listenbrainz user token (listenbrainz.org/settings), to find new songs for each +# genre mix with LB Radio. You can also save it to your account in the web UI, which takes priority. +LISTENBRAINZ_TOKEN= + +# Where to serve playlistd. The first visit to the web UI creates the login, and anyone who gets +# there first can, so it only listens on this machine by default. Once you've created your account, +# set PLAYLISTD_BIND=0.0.0.0 to make it reachable from your network. +PLAYLISTD_BIND=127.0.0.1 +PLAYLISTD_PORT=8000 + +# How often to update playlists, in seconds +DAEMON_INTERVAL=240 +# error, warn, info, debug or trace +LOG_LEVEL=info diff --git a/.sqlx/query-05ea02585c443ea926d13135ed387bc870069fbda7974de6bb1ecbdd1d624294.json b/.sqlx/query-05ea02585c443ea926d13135ed387bc870069fbda7974de6bb1ecbdd1d624294.json new file mode 100644 index 0000000..1d6960a --- /dev/null +++ b/.sqlx/query-05ea02585c443ea926d13135ed387bc870069fbda7974de6bb1ecbdd1d624294.json @@ -0,0 +1,46 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"tracked_playlist\" WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "playlist_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + false, + false, + false + ] + }, + "hash": "05ea02585c443ea926d13135ed387bc870069fbda7974de6bb1ecbdd1d624294" +} diff --git a/.sqlx/query-0fcfce36e362e78c3ff6e17de104a347f417296dd0c8449e4535e545b85cc239.json b/.sqlx/query-0fcfce36e362e78c3ff6e17de104a347f417296dd0c8449e4535e545b85cc239.json new file mode 100644 index 0000000..c68540f --- /dev/null +++ b/.sqlx/query-0fcfce36e362e78c3ff6e17de104a347f417296dd0c8449e4535e545b85cc239.json @@ -0,0 +1,74 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT * FROM \"cluster_mix_rule\"\n WHERE last_run IS NULL OR last_run < NOW() - make_interval(hours => refresh_hours)\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "months", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "cluster_count", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "familiar_ratio", + "type_info": "Float8" + }, + { + "ordinal": 6, + "name": "name_template", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "refresh_hours", + "type_info": "Int4" + }, + { + "ordinal": 8, + "name": "last_run", + "type_info": "Timestamptz" + }, + { + "ordinal": 9, + "name": "discovery_count", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + false, + true, + false + ] + }, + "hash": "0fcfce36e362e78c3ff6e17de104a347f417296dd0c8449e4535e545b85cc239" +} diff --git a/.sqlx/query-140cbe2334178ba5f7f44d5b0998d0a0f7b6e3c12b4a94b8e19f2cbaaf991783.json b/.sqlx/query-140cbe2334178ba5f7f44d5b0998d0a0f7b6e3c12b4a94b8e19f2cbaaf991783.json new file mode 100644 index 0000000..6e64178 --- /dev/null +++ b/.sqlx/query-140cbe2334178ba5f7f44d5b0998d0a0f7b6e3c12b4a94b8e19f2cbaaf991783.json @@ -0,0 +1,49 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE \"tracked_playlist\" SET playlist_size = $1, tracking_user = $2, tracking_type = $3\n WHERE id = $4\n RETURNING *\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "playlist_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Int4", + "Varchar", + "Varchar", + "Uuid" + ] + }, + "nullable": [ + false, + true, + false, + false, + false + ] + }, + "hash": "140cbe2334178ba5f7f44d5b0998d0a0f7b6e3c12b4a94b8e19f2cbaaf991783" +} diff --git a/.sqlx/query-1583d8cb8989b06c29c86a916e7ee8d56c1f28ab8bf4d303338c58d137f58649.json b/.sqlx/query-1583d8cb8989b06c29c86a916e7ee8d56c1f28ab8bf4d303338c58d137f58649.json new file mode 100644 index 0000000..d8d68b1 --- /dev/null +++ b/.sqlx/query-1583d8cb8989b06c29c86a916e7ee8d56c1f28ab8bf4d303338c58d137f58649.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"cluster_mix_playlist\" (id, rule_id, playlist_id, tags, name, position, known_song_ids)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Varchar", + "TextArray", + "Varchar", + "Int4", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "1583d8cb8989b06c29c86a916e7ee8d56c1f28ab8bf4d303338c58d137f58649" +} diff --git a/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json b/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json new file mode 100644 index 0000000..f88b3ec --- /dev/null +++ b/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE \"app_user\" SET listenbrainz_token = $1, listenbrainz_user = $2 WHERE id = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982" +} diff --git a/.sqlx/query-1bec8520afc0ec6b6fd95526afe88aabf8a50f8e11677115b159e5bd5c023dd1.json b/.sqlx/query-1bec8520afc0ec6b6fd95526afe88aabf8a50f8e11677115b159e5bd5c023dd1.json new file mode 100644 index 0000000..ecb8623 --- /dev/null +++ b/.sqlx/query-1bec8520afc0ec6b6fd95526afe88aabf8a50f8e11677115b159e5bd5c023dd1.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) AS \"count!\" FROM \"tracked_playlist\" WHERE playlist_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "1bec8520afc0ec6b6fd95526afe88aabf8a50f8e11677115b159e5bd5c023dd1" +} diff --git a/.sqlx/query-2e7b087b647e892160350acf6a7a802efd4f80b075c1de4ca56822b10433b15d.json b/.sqlx/query-2e7b087b647e892160350acf6a7a802efd4f80b075c1de4ca56822b10433b15d.json new file mode 100644 index 0000000..6e894fb --- /dev/null +++ b/.sqlx/query-2e7b087b647e892160350acf6a7a802efd4f80b075c1de4ca56822b10433b15d.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE \"create_tracked_playlist\" SET last_name = $1 WHERE id = $2\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "2e7b087b647e892160350acf6a7a802efd4f80b075c1de4ca56822b10433b15d" +} diff --git a/.sqlx/query-33eaace52e7378f2a2490f1878e2c5b595c2a841949781f066b69d051cfa0572.json b/.sqlx/query-33eaace52e7378f2a2490f1878e2c5b595c2a841949781f066b69d051cfa0572.json new file mode 100644 index 0000000..fa8c8b4 --- /dev/null +++ b/.sqlx/query-33eaace52e7378f2a2490f1878e2c5b595c2a841949781f066b69d051cfa0572.json @@ -0,0 +1,44 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"tracked_playlist\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "playlist_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + true, + false, + false, + false + ] + }, + "hash": "33eaace52e7378f2a2490f1878e2c5b595c2a841949781f066b69d051cfa0572" +} diff --git a/.sqlx/query-36fa83bf2a9d53cb1099e059365cdb595db27d339c8130ea75e40fa6f3ef17f7.json b/.sqlx/query-36fa83bf2a9d53cb1099e059365cdb595db27d339c8130ea75e40fa6f3ef17f7.json new file mode 100644 index 0000000..9304b2f --- /dev/null +++ b/.sqlx/query-36fa83bf2a9d53cb1099e059365cdb595db27d339c8130ea75e40fa6f3ef17f7.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"tracked_playlist\" (id, playlist_id, playlist_size, tracking_user, tracking_type)\n VALUES ($1, $2, $3, $4, $5)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Int4", + "Varchar", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "36fa83bf2a9d53cb1099e059365cdb595db27d339c8130ea75e40fa6f3ef17f7" +} diff --git a/.sqlx/query-41635dc0ab3a9a89396ef6f8f01da9e0537860ed59c6282d212e8f7d11367dc3.json b/.sqlx/query-41635dc0ab3a9a89396ef6f8f01da9e0537860ed59c6282d212e8f7d11367dc3.json new file mode 100644 index 0000000..ec9b6e2 --- /dev/null +++ b/.sqlx/query-41635dc0ab3a9a89396ef6f8f01da9e0537860ed59c6282d212e8f7d11367dc3.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE \"cluster_mix_rule\" SET last_run = NOW() WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "41635dc0ab3a9a89396ef6f8f01da9e0537860ed59c6282d212e8f7d11367dc3" +} diff --git a/.sqlx/query-4658d306660c08b593097b67d41236e2921eeb39d1e0efe28e0812b66454ca53.json b/.sqlx/query-4658d306660c08b593097b67d41236e2921eeb39d1e0efe28e0812b66454ca53.json new file mode 100644 index 0000000..ac5966f --- /dev/null +++ b/.sqlx/query-4658d306660c08b593097b67d41236e2921eeb39d1e0efe28e0812b66454ca53.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"cluster_mix_rule\"\n (id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours, discovery_count)\n VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24), COALESCE($9, 15))\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Int4", + "Int4", + "Int4", + "Float8", + "Text", + "Int4", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "4658d306660c08b593097b67d41236e2921eeb39d1e0efe28e0812b66454ca53" +} diff --git a/.sqlx/query-48b88b6b5e7e44a170bf3b9b0a4cb120b4654a9bbc35c2993fdb561c580c9f4c.json b/.sqlx/query-48b88b6b5e7e44a170bf3b9b0a4cb120b4654a9bbc35c2993fdb561c580c9f4c.json new file mode 100644 index 0000000..a6334f3 --- /dev/null +++ b/.sqlx/query-48b88b6b5e7e44a170bf3b9b0a4cb120b4654a9bbc35c2993fdb561c580c9f4c.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE \"mix_suggestion\" SET youtube_id = $1 WHERE id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "48b88b6b5e7e44a170bf3b9b0a4cb120b4654a9bbc35c2993fdb561c580c9f4c" +} diff --git a/.sqlx/query-56a1dac7cdd40bec6bf0c559d5e199eba045807441a2732d817c0194fbd69424.json b/.sqlx/query-56a1dac7cdd40bec6bf0c559d5e199eba045807441a2732d817c0194fbd69424.json new file mode 100644 index 0000000..67c7a4a --- /dev/null +++ b/.sqlx/query-56a1dac7cdd40bec6bf0c559d5e199eba045807441a2732d817c0194fbd69424.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"create_tracked_playlist\"\n (id, name_template, playlist_size, tracking_user, tracking_type)\n VALUES ($1, $2, $3, $4, $5)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Int4", + "Varchar", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "56a1dac7cdd40bec6bf0c559d5e199eba045807441a2732d817c0194fbd69424" +} diff --git a/.sqlx/query-6450c8ac3a2b1c2d102e3a51ec0feccb97b5ea657c32c2da9719e33980d29f7c.json b/.sqlx/query-6450c8ac3a2b1c2d102e3a51ec0feccb97b5ea657c32c2da9719e33980d29f7c.json new file mode 100644 index 0000000..12b3136 --- /dev/null +++ b/.sqlx/query-6450c8ac3a2b1c2d102e3a51ec0feccb97b5ea657c32c2da9719e33980d29f7c.json @@ -0,0 +1,58 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"cluster_mix_playlist\" WHERE rule_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "rule_id", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "playlist_id", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "tags", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "position", + "type_info": "Int4" + }, + { + "ordinal": 6, + "name": "known_song_ids", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + false, + false + ] + }, + "hash": "6450c8ac3a2b1c2d102e3a51ec0feccb97b5ea657c32c2da9719e33980d29f7c" +} diff --git a/.sqlx/query-6f7b59596a62c5bc14f256b71d6d043ef91ff2f351b40e5d51347e1b38798e7f.json b/.sqlx/query-6f7b59596a62c5bc14f256b71d6d043ef91ff2f351b40e5d51347e1b38798e7f.json new file mode 100644 index 0000000..685879b --- /dev/null +++ b/.sqlx/query-6f7b59596a62c5bc14f256b71d6d043ef91ff2f351b40e5d51347e1b38798e7f.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT known_song_ids FROM \"cluster_mix_playlist\" WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "known_song_ids", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "6f7b59596a62c5bc14f256b71d6d043ef91ff2f351b40e5d51347e1b38798e7f" +} diff --git a/.sqlx/query-7095fd0a74b32022fee3f232b8ef0b6905b053b9bd60c26796a6e8dd9c279294.json b/.sqlx/query-7095fd0a74b32022fee3f232b8ef0b6905b053b9bd60c26796a6e8dd9c279294.json new file mode 100644 index 0000000..5566e78 --- /dev/null +++ b/.sqlx/query-7095fd0a74b32022fee3f232b8ef0b6905b053b9bd60c26796a6e8dd9c279294.json @@ -0,0 +1,56 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE \"create_tracked_playlist\"\n SET name_template = $1, playlist_size = $2, tracking_user = $3, tracking_type = $4\n WHERE id = $5\n RETURNING *\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name_template", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "last_name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Int4", + "Varchar", + "Varchar", + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + false + ] + }, + "hash": "7095fd0a74b32022fee3f232b8ef0b6905b053b9bd60c26796a6e8dd9c279294" +} diff --git a/.sqlx/query-74d85db3f858a16f3dd38ce53cc5a4666287d8a3fb6e77379601427ffcc74c4c.json b/.sqlx/query-74d85db3f858a16f3dd38ce53cc5a4666287d8a3fb6e77379601427ffcc74c4c.json new file mode 100644 index 0000000..9b9b6cd --- /dev/null +++ b/.sqlx/query-74d85db3f858a16f3dd38ce53cc5a4666287d8a3fb6e77379601427ffcc74c4c.json @@ -0,0 +1,46 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"tracked_playlist\" WHERE id = $1 RETURNING *", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "playlist_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + false, + false, + false + ] + }, + "hash": "74d85db3f858a16f3dd38ce53cc5a4666287d8a3fb6e77379601427ffcc74c4c" +} diff --git a/.sqlx/query-75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0.json b/.sqlx/query-75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0.json new file mode 100644 index 0000000..77cd188 --- /dev/null +++ b/.sqlx/query-75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO \"app_user\" (id, username, password_hash) VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0" +} diff --git a/.sqlx/query-77c9c346440493d8101128b7b3d80ebf987262a4a82d1522a2eed17908c38006.json b/.sqlx/query-77c9c346440493d8101128b7b3d80ebf987262a4a82d1522a2eed17908c38006.json new file mode 100644 index 0000000..031792d --- /dev/null +++ b/.sqlx/query-77c9c346440493d8101128b7b3d80ebf987262a4a82d1522a2eed17908c38006.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT p.id, p.playlist_id, p.name, p.tags, p.position,\n COUNT(s.id) FILTER (WHERE s.status = 'new') AS \"new_count!\"\n FROM \"cluster_mix_playlist\" p\n LEFT JOIN \"mix_suggestion\" s ON s.mix_id = p.id\n WHERE p.id = $1\n GROUP BY p.id\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "playlist_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "tags", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "position", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "new_count!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + null + ] + }, + "hash": "77c9c346440493d8101128b7b3d80ebf987262a4a82d1522a2eed17908c38006" +} diff --git a/.sqlx/query-79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json b/.sqlx/query-79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json new file mode 100644 index 0000000..a66d279 --- /dev/null +++ b/.sqlx/query-79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"user_session\" (token_hash, user_id, expires_at)\n VALUES ($1, $2, NOW() + make_interval(days => $3))\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bytea", + "Uuid", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d" +} diff --git a/.sqlx/query-88dba59ec1da36cfe138eb541821261f221adfdd979006ecbffa4aee45f03380.json b/.sqlx/query-88dba59ec1da36cfe138eb541821261f221adfdd979006ecbffa4aee45f03380.json new file mode 100644 index 0000000..56825d3 --- /dev/null +++ b/.sqlx/query-88dba59ec1da36cfe138eb541821261f221adfdd979006ecbffa4aee45f03380.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE \"cluster_mix_playlist\" SET tags = $1, name = $2, position = $3, known_song_ids = $4 WHERE id = $5", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "TextArray", + "Varchar", + "Int4", + "TextArray", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "88dba59ec1da36cfe138eb541821261f221adfdd979006ecbffa4aee45f03380" +} diff --git a/.sqlx/query-8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7.json b/.sqlx/query-8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7.json new file mode 100644 index 0000000..5dc751b --- /dev/null +++ b/.sqlx/query-8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT * FROM \"mix_suggestion\"\n WHERE mix_id = $1 AND status <> 'dismissed'\n ORDER BY score DESC\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "rule_id", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "mix_id", + "type_info": "Uuid" + }, + { + "ordinal": 3, + "name": "recording_mbid", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "title", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "artist", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "release", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "cover_url", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "score", + "type_info": "Float8" + }, + { + "ordinal": 9, + "name": "status", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "youtube_id", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "created_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + true, + false + ] + }, + "hash": "8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7" +} diff --git a/.sqlx/query-8c19ada023a49ab9ca540746e3f0abee811969797d4fe137b24180b0aedf7261.json b/.sqlx/query-8c19ada023a49ab9ca540746e3f0abee811969797d4fe137b24180b0aedf7261.json new file mode 100644 index 0000000..3b76d41 --- /dev/null +++ b/.sqlx/query-8c19ada023a49ab9ca540746e3f0abee811969797d4fe137b24180b0aedf7261.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"create_tracked_playlist\" WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "8c19ada023a49ab9ca540746e3f0abee811969797d4fe137b24180b0aedf7261" +} diff --git a/.sqlx/query-9ba02bb97145e9ed2537e1bf90602ede03b35e002de863499b1f97a0542adbdc.json b/.sqlx/query-9ba02bb97145e9ed2537e1bf90602ede03b35e002de863499b1f97a0542adbdc.json new file mode 100644 index 0000000..37f444f --- /dev/null +++ b/.sqlx/query-9ba02bb97145e9ed2537e1bf90602ede03b35e002de863499b1f97a0542adbdc.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT recording_mbid FROM \"mix_suggestion\" WHERE rule_id = $1 AND status <> 'new'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "recording_mbid", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "9ba02bb97145e9ed2537e1bf90602ede03b35e002de863499b1f97a0542adbdc" +} diff --git a/.sqlx/query-9fdbbd0e6140667f887fd9d6fda303bbde3eea38f504dde4d2368f642d5f66ba.json b/.sqlx/query-9fdbbd0e6140667f887fd9d6fda303bbde3eea38f504dde4d2368f642d5f66ba.json new file mode 100644 index 0000000..359a6a6 --- /dev/null +++ b/.sqlx/query-9fdbbd0e6140667f887fd9d6fda303bbde3eea38f504dde4d2368f642d5f66ba.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT playlist_id FROM \"cluster_mix_playlist\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "playlist_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false + ] + }, + "hash": "9fdbbd0e6140667f887fd9d6fda303bbde3eea38f504dde4d2368f642d5f66ba" +} diff --git a/.sqlx/query-a169afa22d2554172b36106b1fb7715b7c2e96276a5714c2dc111090bcedce4e.json b/.sqlx/query-a169afa22d2554172b36106b1fb7715b7c2e96276a5714c2dc111090bcedce4e.json new file mode 100644 index 0000000..de6ee77 --- /dev/null +++ b/.sqlx/query-a169afa22d2554172b36106b1fb7715b7c2e96276a5714c2dc111090bcedce4e.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"cluster_mix_playlist\" WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "a169afa22d2554172b36106b1fb7715b7c2e96276a5714c2dc111090bcedce4e" +} diff --git a/.sqlx/query-a2346e8590c9e5af908647270424e5d9ab3212b1c6aa896dd8a9dbe081d142a3.json b/.sqlx/query-a2346e8590c9e5af908647270424e5d9ab3212b1c6aa896dd8a9dbe081d142a3.json new file mode 100644 index 0000000..d92e2fb --- /dev/null +++ b/.sqlx/query-a2346e8590c9e5af908647270424e5d9ab3212b1c6aa896dd8a9dbe081d142a3.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"mix_suggestion\" (id, rule_id, mix_id, recording_mbid, title, artist, release, cover_url, score)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ON CONFLICT (rule_id, recording_mbid) DO UPDATE\n SET mix_id = EXCLUDED.mix_id, score = EXCLUDED.score, title = EXCLUDED.title,\n artist = EXCLUDED.artist, release = EXCLUDED.release, cover_url = EXCLUDED.cover_url\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Uuid", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Text", + "Float8" + ] + }, + "nullable": [] + }, + "hash": "a2346e8590c9e5af908647270424e5d9ab3212b1c6aa896dd8a9dbe081d142a3" +} diff --git a/.sqlx/query-a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332.json b/.sqlx/query-a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332.json new file mode 100644 index 0000000..5137664 --- /dev/null +++ b/.sqlx/query-a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"user_session\" WHERE expires_at <= NOW()", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332" +} diff --git a/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json b/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json new file mode 100644 index 0000000..57a8942 --- /dev/null +++ b/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT listenbrainz_token AS \"token!\" FROM \"app_user\"\n WHERE listenbrainz_token IS NOT NULL\n ORDER BY created_at\n LIMIT 1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "token!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true + ] + }, + "hash": "a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9" +} diff --git a/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json b/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json new file mode 100644 index 0000000..63c13a3 --- /dev/null +++ b/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT username, listenbrainz_user, listenbrainz_token IS NOT NULL AS \"has_listenbrainz_token!\"\n FROM \"app_user\" WHERE id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "listenbrainz_user", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "has_listenbrainz_token!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + null + ] + }, + "hash": "a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4" +} diff --git a/.sqlx/query-ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d.json b/.sqlx/query-ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d.json new file mode 100644 index 0000000..c74ef51 --- /dev/null +++ b/.sqlx/query-ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "LOCK TABLE \"app_user\" IN SHARE ROW EXCLUSIVE MODE", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d" +} diff --git a/.sqlx/query-b37554160321e4336291a0ba3e98678dca5219645f0cc8a37ceaf3e3679c96e5.json b/.sqlx/query-b37554160321e4336291a0ba3e98678dca5219645f0cc8a37ceaf3e3679c96e5.json new file mode 100644 index 0000000..be0331b --- /dev/null +++ b/.sqlx/query-b37554160321e4336291a0ba3e98678dca5219645f0cc8a37ceaf3e3679c96e5.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"tracked_playlist\"\n (id, playlist_id, playlist_size, tracking_user, tracking_type)\n VALUES ($1, $2, $3, $4, $5)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Int4", + "Varchar", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "b37554160321e4336291a0ba3e98678dca5219645f0cc8a37ceaf3e3679c96e5" +} diff --git a/.sqlx/query-b4cf9d01b38e1aa1e453d864e4003a67168db182c402bae84f466f57a2943210.json b/.sqlx/query-b4cf9d01b38e1aa1e453d864e4003a67168db182c402bae84f466f57a2943210.json new file mode 100644 index 0000000..24b0876 --- /dev/null +++ b/.sqlx/query-b4cf9d01b38e1aa1e453d864e4003a67168db182c402bae84f466f57a2943210.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "\n DELETE FROM \"mix_suggestion\"\n WHERE rule_id = $1 AND status = 'new' AND NOT (recording_mbid = ANY($2))\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "b4cf9d01b38e1aa1e453d864e4003a67168db182c402bae84f466f57a2943210" +} diff --git a/.sqlx/query-bab5fa268127c47d676d45f80d1b404b9eddce632b2d2e5af71009b3698209db.json b/.sqlx/query-bab5fa268127c47d676d45f80d1b404b9eddce632b2d2e5af71009b3698209db.json new file mode 100644 index 0000000..56fbf60 --- /dev/null +++ b/.sqlx/query-bab5fa268127c47d676d45f80d1b404b9eddce632b2d2e5af71009b3698209db.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE \"cluster_mix_rule\" SET last_run = NULL WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "bab5fa268127c47d676d45f80d1b404b9eddce632b2d2e5af71009b3698209db" +} diff --git a/.sqlx/query-c765601bb917b3528b6ec0715c4f546257b87f4bd292cfe2ecf7718b9b633ba8.json b/.sqlx/query-c765601bb917b3528b6ec0715c4f546257b87f4bd292cfe2ecf7718b9b633ba8.json new file mode 100644 index 0000000..b544182 --- /dev/null +++ b/.sqlx/query-c765601bb917b3528b6ec0715c4f546257b87f4bd292cfe2ecf7718b9b633ba8.json @@ -0,0 +1,76 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"cluster_mix_rule\" WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "months", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "cluster_count", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "familiar_ratio", + "type_info": "Float8" + }, + { + "ordinal": 6, + "name": "name_template", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "refresh_hours", + "type_info": "Int4" + }, + { + "ordinal": 8, + "name": "last_run", + "type_info": "Timestamptz" + }, + { + "ordinal": 9, + "name": "discovery_count", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + false, + true, + false + ] + }, + "hash": "c765601bb917b3528b6ec0715c4f546257b87f4bd292cfe2ecf7718b9b633ba8" +} diff --git a/.sqlx/query-cfae5ae8ede031ca7f575de374e7168599c81e61d3718b8793ef46dd06ddf4ff.json b/.sqlx/query-cfae5ae8ede031ca7f575de374e7168599c81e61d3718b8793ef46dd06ddf4ff.json new file mode 100644 index 0000000..7ed22f7 --- /dev/null +++ b/.sqlx/query-cfae5ae8ede031ca7f575de374e7168599c81e61d3718b8793ef46dd06ddf4ff.json @@ -0,0 +1,56 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"create_tracked_playlist\" (id, name_template, playlist_size, tracking_user, tracking_type)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING *\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name_template", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "last_name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Int4", + "Varchar", + "Varchar" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + false + ] + }, + "hash": "cfae5ae8ede031ca7f575de374e7168599c81e61d3718b8793ef46dd06ddf4ff" +} diff --git a/.sqlx/query-cff3fd3c455a6accdde8cc5b258ab80a934afa8f6a9003101ab9a7f0c659ac9c.json b/.sqlx/query-cff3fd3c455a6accdde8cc5b258ab80a934afa8f6a9003101ab9a7f0c659ac9c.json new file mode 100644 index 0000000..985cf4d --- /dev/null +++ b/.sqlx/query-cff3fd3c455a6accdde8cc5b258ab80a934afa8f6a9003101ab9a7f0c659ac9c.json @@ -0,0 +1,74 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"cluster_mix_rule\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "months", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "cluster_count", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "familiar_ratio", + "type_info": "Float8" + }, + { + "ordinal": 6, + "name": "name_template", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "refresh_hours", + "type_info": "Int4" + }, + { + "ordinal": 8, + "name": "last_run", + "type_info": "Timestamptz" + }, + { + "ordinal": 9, + "name": "discovery_count", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + false, + true, + false + ] + }, + "hash": "cff3fd3c455a6accdde8cc5b258ab80a934afa8f6a9003101ab9a7f0c659ac9c" +} diff --git a/.sqlx/query-d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635.json b/.sqlx/query-d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635.json new file mode 100644 index 0000000..1e833bd --- /dev/null +++ b/.sqlx/query-d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT user_id FROM \"user_session\" WHERE token_hash = $1 AND expires_at > NOW()", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "user_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Bytea" + ] + }, + "nullable": [ + false + ] + }, + "hash": "d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635" +} diff --git a/.sqlx/query-d16da81d740f05ee4a80d5f02823a8ee73e6bfd4dee35fb8df50651af8bcb8b6.json b/.sqlx/query-d16da81d740f05ee4a80d5f02823a8ee73e6bfd4dee35fb8df50651af8bcb8b6.json new file mode 100644 index 0000000..3379603 --- /dev/null +++ b/.sqlx/query-d16da81d740f05ee4a80d5f02823a8ee73e6bfd4dee35fb8df50651af8bcb8b6.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"tracked_playlist\" (id, playlist_id, playlist_size, tracking_user, tracking_type)\n VALUES ($1, $2, $3, $4, $5)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Int4", + "Varchar", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "d16da81d740f05ee4a80d5f02823a8ee73e6bfd4dee35fb8df50651af8bcb8b6" +} diff --git a/.sqlx/query-d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76.json b/.sqlx/query-d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76.json new file mode 100644 index 0000000..b8f0a87 --- /dev/null +++ b/.sqlx/query-d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT * FROM \"mix_suggestion\"\n WHERE rule_id = $1 AND status = 'liked'\n ORDER BY created_at DESC\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "rule_id", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "mix_id", + "type_info": "Uuid" + }, + { + "ordinal": 3, + "name": "recording_mbid", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "title", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "artist", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "release", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "cover_url", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "score", + "type_info": "Float8" + }, + { + "ordinal": 9, + "name": "status", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "youtube_id", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "created_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + true, + false + ] + }, + "hash": "d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76" +} diff --git a/.sqlx/query-d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9.json b/.sqlx/query-d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9.json new file mode 100644 index 0000000..c2f3ab2 --- /dev/null +++ b/.sqlx/query-d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"mix_suggestion\" WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "rule_id", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "mix_id", + "type_info": "Uuid" + }, + { + "ordinal": 3, + "name": "recording_mbid", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "title", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "artist", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "release", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "cover_url", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "score", + "type_info": "Float8" + }, + { + "ordinal": 9, + "name": "status", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "youtube_id", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "created_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + true, + false + ] + }, + "hash": "d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9" +} diff --git a/.sqlx/query-e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b.json b/.sqlx/query-e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b.json new file mode 100644 index 0000000..474f978 --- /dev/null +++ b/.sqlx/query-e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b.json @@ -0,0 +1,89 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE \"mix_suggestion\" SET status = $1 WHERE id = $2 RETURNING *", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "rule_id", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "mix_id", + "type_info": "Uuid" + }, + { + "ordinal": 3, + "name": "recording_mbid", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "title", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "artist", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "release", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "cover_url", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "score", + "type_info": "Float8" + }, + { + "ordinal": 9, + "name": "status", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "youtube_id", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "created_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + true, + false + ] + }, + "hash": "e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b" +} diff --git a/.sqlx/query-ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3.json b/.sqlx/query-ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3.json new file mode 100644 index 0000000..9b8ecb4 --- /dev/null +++ b/.sqlx/query-ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM \"app_user\") AS \"e!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "e!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3" +} diff --git a/.sqlx/query-f25088f17025ed1b1e7e9babdf5af0ac876c36e7b580930ac129d03a8400f34c.json b/.sqlx/query-f25088f17025ed1b1e7e9babdf5af0ac876c36e7b580930ac129d03a8400f34c.json new file mode 100644 index 0000000..ee91a87 --- /dev/null +++ b/.sqlx/query-f25088f17025ed1b1e7e9babdf5af0ac876c36e7b580930ac129d03a8400f34c.json @@ -0,0 +1,50 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"create_tracked_playlist\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name_template", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "last_name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + true, + false, + false, + false + ] + }, + "hash": "f25088f17025ed1b1e7e9babdf5af0ac876c36e7b580930ac129d03a8400f34c" +} diff --git a/.sqlx/query-f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916.json b/.sqlx/query-f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916.json new file mode 100644 index 0000000..88a0bca --- /dev/null +++ b/.sqlx/query-f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"user_session\" WHERE token_hash = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bytea" + ] + }, + "nullable": [] + }, + "hash": "f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916" +} diff --git a/.sqlx/query-faab358eedf40841a9aea533f8b1cf77fe0ce20f9ab5353672cbcb92e8d7f649.json b/.sqlx/query-faab358eedf40841a9aea533f8b1cf77fe0ce20f9ab5353672cbcb92e8d7f649.json new file mode 100644 index 0000000..3f235e7 --- /dev/null +++ b/.sqlx/query-faab358eedf40841a9aea533f8b1cf77fe0ce20f9ab5353672cbcb92e8d7f649.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT * FROM \"create_tracked_playlist\" WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name_template", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "last_name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "playlist_size", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "tracking_user", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "tracking_type", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + false + ] + }, + "hash": "faab358eedf40841a9aea533f8b1cf77fe0ce20f9ab5353672cbcb92e8d7f649" +} diff --git a/.sqlx/query-fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b.json b/.sqlx/query-fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b.json new file mode 100644 index 0000000..4996e27 --- /dev/null +++ b/.sqlx/query-fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, password_hash FROM \"app_user\" WHERE username = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "password_hash", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b" +} diff --git a/.sqlx/query-fe496006c6b38d578b6246ddcabf9ef08d36817fe2e0514a46a9ea8eb0f4a7f9.json b/.sqlx/query-fe496006c6b38d578b6246ddcabf9ef08d36817fe2e0514a46a9ea8eb0f4a7f9.json new file mode 100644 index 0000000..774413f --- /dev/null +++ b/.sqlx/query-fe496006c6b38d578b6246ddcabf9ef08d36817fe2e0514a46a9ea8eb0f4a7f9.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT p.id, p.playlist_id, p.name, p.tags, p.position,\n COUNT(s.id) FILTER (WHERE s.status = 'new') AS \"new_count!\"\n FROM \"cluster_mix_playlist\" p\n LEFT JOIN \"mix_suggestion\" s ON s.mix_id = p.id\n WHERE p.rule_id = $1\n GROUP BY p.id\n ORDER BY p.position\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "playlist_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "tags", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "position", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "new_count!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + false, + false, + null + ] + }, + "hash": "fe496006c6b38d578b6246ddcabf9ef08d36817fe2e0514a46a9ea8eb0f4a7f9" +} diff --git a/Cargo.lock b/Cargo.lock index b958693..153e507 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -47,6 +47,68 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + [[package]] name = "arraydeque" version = "0.5.1" @@ -170,6 +232,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -229,10 +300,17 @@ dependencies = [ "iana-time-zone", "js-sys", "num-traits", + "serde", "wasm-bindgen", "windows-targets 0.52.5", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -477,6 +555,29 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + [[package]] name = "equivalent" version = "1.0.1" @@ -663,6 +764,17 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +[[package]] +name = "futures-macro" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "futures-sink" version = "0.3.30" @@ -684,6 +796,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -966,12 +1079,53 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +[[package]] +name = "jiff" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" +dependencies = [ + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "js-sys" version = "0.3.83" @@ -1042,9 +1196,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.21" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "loom" @@ -1243,6 +1397,12 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "openssl" version = "0.10.75" @@ -1332,6 +1492,17 @@ dependencies = [ "windows-targets 0.48.5", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + [[package]] name = "pathdiff" version = "0.2.3" @@ -1464,19 +1635,41 @@ checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" name = "playlistd" version = "0.2.6" dependencies = [ + "argon2", "chrono", "config", + "env_logger", + "futures-util", "log", "md5", + "rand", "reqwest", "rocket", "serde", + "serde_json", + "sha2", "sqlx", "thiserror 2.0.17", "tokio", + "tokio-util", "uuid", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -1513,9 +1706,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.36" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -1581,14 +1774,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.4" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.6", - "regex-syntax 0.8.3", + "regex-automata 0.4.18", + "regex-syntax 0.8.11", ] [[package]] @@ -1602,13 +1795,13 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.6" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.3", + "regex-syntax 0.8.11", ] [[package]] @@ -1619,9 +1812,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.3" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "reqwest" @@ -1655,10 +1848,12 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", + "tokio-util", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", "winreg", ] @@ -2088,6 +2283,7 @@ checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" dependencies = [ "base64 0.22.1", "bytes", + "chrono", "crc", "crossbeam-queue", "either", @@ -2164,6 +2360,7 @@ dependencies = [ "bitflags 2.10.0", "byteorder", "bytes", + "chrono", "crc", "digest", "dotenvy", @@ -2206,6 +2403,7 @@ dependencies = [ "base64 0.22.1", "bitflags 2.10.0", "byteorder", + "chrono", "crc", "dotenvy", "etcetera", @@ -2241,6 +2439,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" dependencies = [ "atoi", + "chrono", "flume", "futures-channel", "futures-core", @@ -2734,6 +2933,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.8.0" @@ -2840,6 +3045,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e072d4e72f700fb3443d8fe94a39315df013eef1104903cdb0a2abd322bbecd" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.69" @@ -2900,6 +3118,12 @@ dependencies = [ "windows-targets 0.52.5", ] +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + [[package]] name = "windows-sys" version = "0.48.0" @@ -2918,6 +3142,15 @@ dependencies = [ "windows-targets 0.52.5", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.48.5" diff --git a/Cargo.toml b/Cargo.toml index 1b1cfd7..2f90b3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,20 +9,32 @@ description = "Subsonic playlist daemon" [dependencies] rocket = { version = "0.5.0", features = ["json"] } tokio = { version = "1.0", features = ["full"] } -sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid"] } -reqwest = { version = "0.11", features = ["json"] } +sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid", "chrono"] } +reqwest = { version = "0.11", features = ["json", "stream"] } serde = { version = "1.0", features = ["derive"] } uuid = { version = "1.7", features = ["v4", "serde"] } md5 = "0.8.0" thiserror = "2.0.17" config = "0.15.19" log = "0.4.21" -chrono = "0.4.38" +env_logger = "0.11" +chrono = { version = "0.4.38", features = ["serde"] } +rand = "0.8" +serde_json = "1.0" +futures-util = "0.3" +tokio-util = { version = "0.7", features = ["io"] } +argon2 = "0.5" +sha2 = "0.10" [package.metadata.deb] depends = "$auto" +# plays suggested songs from YouTube. Distribution packages may be too old to work with YouTube, +# so it's only recommended: a current yt-dlp from elsewhere (e.g. pip) works too +recommends = "yt-dlp" assets = [ ["target/release/playlistd", "usr/bin/playlistd", "755"], + # the web UI; build it first with `npm --prefix discover ci && npm --prefix discover run build` + ["discover/dist/**/*", "usr/share/playlistd/discover/", "644"], ["etc/playlistd/playlistd.toml", "etc/playlistd/playlistd.toml", "600"], ["etc/playlistd/Rocket.toml", "etc/playlistd/Rocket.toml", "600"], ] diff --git a/Containerfile b/Containerfile index 6779759..a623f90 100644 --- a/Containerfile +++ b/Containerfile @@ -4,6 +4,17 @@ ENV RUSTUP_HOME=/usr/local/rustup \ CARGO_HOME=/usr/local/cargo \ PATH=/usr/local/cargo/bin:$PATH -RUN apt update && DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt install -y gcc gcc-multilib cmake pkg-config libssl-dev curl dpkg-dev +RUN apt update && DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt install -y gcc gcc-multilib cmake pkg-config libssl-dev curl dpkg-dev xz-utils RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --profile minimal --default-toolchain nightly RUN cargo install cargo-deb + +# Node.js, to build the web UI (Ubuntu 22.04's is too old for Vite) +ARG NODE_VERSION=22.23.4 +RUN arch="$(dpkg --print-architecture | sed 's/amd64/x64/')" \ + && file="node-v${NODE_VERSION}-linux-${arch}.tar.xz" \ + && cd /tmp \ + && curl -fsSLO "https://nodejs.org/dist/v${NODE_VERSION}/${file}" \ + && curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/SHASUMS256.txt" | grep " ${file}\$" | sha256sum -c - \ + && tar -xJf "${file}" -C /usr/local --strip-components=1 --no-same-owner \ + && rm "${file}" \ + && node --version diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..adf71b9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,48 @@ +# Image for running playlistd, used by compose.yaml. (Containerfile is for building the .deb.) + +# ---- web UI ---- +FROM node:22.23.4-bookworm-slim AS ui +WORKDIR /src +COPY discover/package.json discover/package-lock.json ./ +RUN npm ci +COPY discover/ ./ +RUN npm run build + +# ---- server ---- +FROM rust:1.97-bookworm AS server +WORKDIR /src +COPY Cargo.toml Cargo.lock ./ +COPY .sqlx .sqlx +COPY migrations migrations +COPY src src +# check SQL queries against .sqlx (made by `cargo sqlx prepare`) rather than a live database +ENV SQLX_OFFLINE=true +RUN cargo build --release --locked + +# ---- runtime ---- +FROM debian:bookworm-slim +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates libssl3 python3 python3-venv \ + && rm -rf /var/lib/apt/lists/* + +# yt-dlp plays suggested songs from YouTube. It has to be recent to keep working with YouTube, so +# the latest version is installed: rebuild the image to update it, or set YTDLP_VERSION to pin one. +ARG YTDLP_VERSION= +RUN python3 -m venv /opt/yt-dlp \ + && /opt/yt-dlp/bin/pip install --no-cache-dir "yt-dlp[default]${YTDLP_VERSION:+==${YTDLP_VERSION}}" \ + && ln -s /opt/yt-dlp/bin/yt-dlp /usr/local/bin/yt-dlp +# yt-dlp needs a JavaScript runtime for YouTube; Deno is the one it uses by default +COPY --from=denoland/deno:bin-2.9.8 /deno /usr/local/bin/deno + +COPY --from=server /src/target/release/playlistd /usr/local/bin/playlistd +COPY --from=ui /src/dist /usr/share/playlistd/discover + +RUN useradd --system --create-home --home-dir /var/lib/playlistd playlistd +USER playlistd +WORKDIR /var/lib/playlistd + +ENV ROCKET_ADDRESS=0.0.0.0 \ + ROCKET_PORT=8000 \ + DISCOVER_UI=/usr/share/playlistd/discover +EXPOSE 8000 +CMD ["playlistd"] diff --git a/README.md b/README.md index 90ce54c..dc3b0a4 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,37 @@ environment variables: For deploying, these can be configured in `/etc/playlistd.toml`. +SQL queries are checked at compile time, against the database in `DATABASE_URL` if it's set, or +otherwise against the query data in `.sqlx/`. After changing a query, update that with +`cargo sqlx prepare` (from `cargo install sqlx-cli`) and commit it. + +### Docker Compose + +`compose.yaml` runs playlistd with its own Postgres database. The image includes the web UI, +yt-dlp and Deno (which yt-dlp needs for YouTube). + +```sh +cp .env.example .env # then fill in your Subsonic server and a database password +docker compose up -d --build +``` + +The web UI is then at http://localhost:8000. The first visit asks you to create an account (see +[Logging in](#logging-in)), and anyone who reaches it first can, so it only listens on the Docker +host by default: create your account, then set `PLAYLISTD_BIND=0.0.0.0` in `.env` to open it to +your network. If your +Subsonic server runs on the Docker host, use `http://host.docker.internal:4533/rest` as +`SUBSONIC_BASE`. + +YouTube changes often break older yt-dlp versions, and the image installs the latest one when it's +built, so rebuild it now and then to keep new songs playing: + +```sh +docker compose build --pull && docker compose up -d +``` + +With podman, use `podman compose`, or build the image with `podman build -f Dockerfile .`: on its +own, `podman build` picks `Containerfile`, which builds the `.deb` below. + ### Container build (Ubuntu 22.04) Build the image: @@ -26,24 +57,44 @@ Build the image: podman build -t playlistd-22 -f Containerfile . ``` -Then build the `.deb`. The `sqlx` query macros check queries against a live, migrated database at -compile time, so the host's Postgres socket is mounted into the container. With rootless podman, the -container's root maps to your host user, so local peer authentication works without a password: +Then build the web UI and the `.deb`. The `sqlx` query macros check queries against a live, +migrated database at compile time, so the host's Postgres socket is mounted into the container. With +rootless podman, the container's root maps to your host user, so local peer authentication works +without a password: ```sh podman run --rm \ -v "$PWD":/mnt -w /mnt \ -v /var/run/postgresql:/var/run/postgresql \ -e DATABASE_URL='postgres://jude@%2Fvar%2Frun%2Fpostgresql/playlistd' \ - playlistd-22 cargo deb + playlistd-22 sh -c 'npm --prefix discover ci && npm --prefix discover run build && cargo deb' ``` -The package is written to `target/debian/`. +The package is written to `target/debian/`. It installs the web UI to `/usr/share/playlistd/discover`, +which the default config serves at `/`. `cargo deb` refuses to build the package if the UI hasn't been +built. + +The package recommends `yt-dlp`, for playing suggested songs from YouTube. Distribution packages of +yt-dlp are often too old to work with YouTube, so you may want a current one instead, e.g. from pip. + +### Logging + +playlistd logs to stdout. Set the level with `log.level` in `playlistd.toml` (or `LOG_LEVEL`): +`error`, `warn`, `info` (the default), `debug` or `trace`. `RUST_LOG` overrides it for finer control, +e.g. `RUST_LOG=playlistd=debug` to also see which top songs couldn't be found in your library. + +Under systemd, lines are tagged with their priority, so `journalctl -u playlistd -p warning` shows +just the problems. A failure that keeps happening (say, a tracked playlist for a Listenbrainz user +that doesn't exist) is logged as a warning once, and again only if the error changes; recovering +from it is logged too. ## How to use Each of these will work best when your music library is well organised with Musicbrainz metadata. +Tracked playlists, recurring playlists and genre mixes can all be managed from the web UI (see +[Discover UI](#discover-ui)), under "Tracked playlists". The SQL below does the same by hand. + ### Tracked playlist A tracked playlist is a single Subsonic playlist that tracks data from Listenbrainz. For example, @@ -63,3 +114,155 @@ For a yearly top songs playlist, run the following: INSERT INTO create_tracked_playlist (id, name_template, playlist_size, tracking_user, tracking_type) VALUES (gen_random_uuid(), '%Y - Top 100', 100, 'jellywx', 'this_year'); ``` + +### Genre mixes + +A cluster mix rule groups the tracks you've listened to over the last few months by genre, and +keeps one Subsonic playlist ("mix") per group, filled with songs from your library. + +How it works: + +1. Your listens for the period are fetched from Listenbrainz, along with the MusicBrainz genres of + each recording, its release group and its artists. +2. Tracks are clustered on their genres. Tracks you tend to play in the same listening session are + pulled closer together, so untagged tracks and genre-hopping artists land with what you play + them next to. The number of clusters is chosen automatically unless you set one. +3. Each cluster's most characteristic genres are matched against your library's genres + (`getGenres` / `getSongsByGenre`), case and punctuation insensitively, so a library tagged with + MusicBrainz genres by Picard works best. +4. Each mix is made of the cluster's most played tracks (`familiar_ratio` of the mix), plus songs + from the matching genres that you haven't played in the period, picked at random weighted by + how well their genres fit, with at most `playlist_size / 8` songs per artist. + +Mixes are rebuilt every `refresh_hours`. On a rebuild, existing mix playlists are reused for the +new cluster with the most similar genres (and renamed), new playlists are created for new +clusters, and playlists for clusters that no longer appear are deleted. + +Create a rule through the API (after logging in, see [Logging in](#logging-in)): + +```sh +curl -b cookies -X POST localhost:8000/api/playlist/mix -H 'Content-Type: application/json' \ + -d '{"tracking_user": "jellywx", "months": 3, "playlist_size": 50}' +``` + +or with SQL: + +```sql +INSERT INTO cluster_mix_rule (id, tracking_user, months, playlist_size) +VALUES (gen_random_uuid(), 'jellywx', 3, 50); +``` + +| Column | Default | Meaning | +|------------------|-----------------|--------------------------------------------------------------| +| `months` | 3 | Months of listening history to cluster | +| `cluster_count` | automatic | Number of mixes | +| `playlist_size` | 50 | Songs per mix | +| `familiar_ratio` | 0.3 | Share of each mix made of songs you've played recently (also used by the discover UI's "Play mix") | +| `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres | +| `refresh_hours` | 24 | How often to rebuild the mixes | +| `discovery_count`| 15 | New songs (not in your library) to suggest per mix | + +Set `last_run` to `NULL` to rebuild a rule's mixes on the next daemon tick. + +### Discover UI + +`discover/` is a React app for listening to the genre mixes, alongside new songs that aren't in +your library yet. + +Each time the mixes are rebuilt, playlistd also looks for new songs for each mix: + +* your Listenbrainz recommendations, keeping only recordings you've never listened to, and +* if a Listenbrainz token is saved to your account (or `listenbrainz.token` is set), an LB Radio + playlist for each mix's top genres. + +Every candidate's MusicBrainz genres are compared with each mix's, and it's suggested in the mix +it fits best (if it fits well enough), skipping songs already in your library. + +In the UI, songs from your library stream from Subsonic. New songs are found on YouTube with +[yt-dlp](https://github.com/yt-dlp/yt-dlp) and streamed through playlistd, so yt-dlp needs to be +installed on the server (keep it up to date: YouTube changes often break older versions). You can +like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again. + +"Play mix" plays a mix's new songs in random order with songs you already know (the songs in the +mix you've played recently) mixed in evenly, so that `familiar_ratio` of what you hear is familiar. +If a mix has too few known songs to keep that ratio, all of them are used. + +The `.deb` includes it (see [Container build](#container-build-ubuntu-2204)). To run it from a +checkout, build it with: + +```sh +cd discover +npm ci +npm run build +``` + +and set `discover.ui` (or `DISCOVER_UI`) to the `discover/dist` directory to serve it from +playlistd at `/`. For development, `npm run dev` serves the UI with hot reload and forwards API +requests to playlistd on `localhost:8000` (or `PLAYLISTD_URL`). + +### Logging in + +The web UI and every API endpoint need you to log in. There's no default account: the first time +anyone opens the UI, it asks for a username and password, and creates the account with them. After +that, the UI shows a login page instead, and new accounts can't be created. Passwords are stored as +Argon2id hashes in the `app_user` table, and logging in sets a session cookie that lasts 30 days. + +To start over (e.g. if you forget your password), delete the account, and the next visit to the UI +will set it up again: + +```sql +DELETE FROM app_user; +``` + +Under the account page in the UI (your username, in the sidebar), you can save your Listenbrainz +user token to your account. It's checked with Listenbrainz first, and is then used instead of +`listenbrainz.token` from the config. + +To use the API from a script, log in with a cookie jar and pass it with each request: + +```sh +curl -c cookies -X POST localhost:8000/api/auth/login -H 'Content-Type: application/json' \ + -d '{"username": "you", "password": "your password"}' +curl -b cookies localhost:8000/api/tracked/playlists +``` + +Requests without a valid session get `401 {"error": "Log in to continue"}`. These endpoints are +under `/api/auth`: + +| Endpoint | Purpose | +|------------------------------|---------------------------------------------------------------| +| `GET /status` | Whether the account still has to be set up, and who's logged in | +| `POST /setup` | Create the account (`username`, `password`), only if there isn't one | +| `POST /login` | Log in (`username`, `password`) | +| `POST /logout` | Log out | +| `GET /account` | The logged in account | +| `PUT /account/listenbrainz` | Save a Listenbrainz `token` to the account (empty removes it) | + +### Endpoints + +The UI uses these endpoints under `/api/discover`: + +| Endpoint | Purpose | +|--------------------------------|------------------------------------------------------| +| `GET /rules` | Cluster mix rules | +| `GET /rules//mixes` | A rule's mixes | +| `GET /mixes/` | A mix's library songs and new song suggestions | +| `GET /rules//liked` | Liked suggestions | +| `PUT /suggestions/` | Set a suggestion's status (`new`, `liked`, `dismissed`) | +| `POST /rules//rebuild` | Rebuild a rule's mixes on the next daemon tick | +| `GET /stream/` | Stream a library song from Subsonic | +| `GET /cover/` | Library cover art from Subsonic | +| `GET /youtube/` | Stream a suggested song from YouTube | + +and these under `/api/tracked` for tracked playlists: + +| Endpoint | Purpose | +|-----------------------------------|------------------------------------------------------------| +| `GET /playlists` | Tracked playlists, with their names and song counts | +| `POST /playlists` | Track an existing playlist (`playlist_id`) or a new one (`name`) | +| `PUT /playlists/` | Change size, user or period; rename with `name` | +| `DELETE /playlists/?delete_playlist=true` | Stop tracking, optionally deleting the playlist | +| `POST /playlists//refresh` | Update a playlist's songs now | +| `GET /subsonic-playlists` | Playlists that can be tracked | +| `GET`/`POST /rules`, `PUT`/`DELETE /rules/` | Recurring playlist rules | +| `GET /preview-name?template=` | What a name template produces today | diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..832d9c0 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,47 @@ +# playlistd and its database. Copy .env.example to .env, fill it in, then run: +# docker compose up -d --build +name: playlistd + +services: + playlistd: + build: + context: . + # podman would otherwise pick Containerfile, which builds the .deb + dockerfile: Dockerfile + image: playlistd + restart: unless-stopped + depends_on: + db: + condition: service_healthy + ports: + # the first visit creates the login, so by default it's only reachable from this machine + - "${PLAYLISTD_BIND:-127.0.0.1}:${PLAYLISTD_PORT:-8000}:8000" + environment: + DATABASE_URL: postgres://playlistd:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@db/playlistd + SUBSONIC_BASE: ${SUBSONIC_BASE:?Set SUBSONIC_BASE in .env} + SUBSONIC_USERNAME: ${SUBSONIC_USERNAME:?Set SUBSONIC_USERNAME in .env} + SUBSONIC_PASSWORD: ${SUBSONIC_PASSWORD:?Set SUBSONIC_PASSWORD in .env} + LISTENBRAINZ_TOKEN: ${LISTENBRAINZ_TOKEN:-} + DAEMON_INTERVAL: ${DAEMON_INTERVAL:-240} + LOG_LEVEL: ${LOG_LEVEL:-info} + # lets SUBSONIC_BASE point at a server on the Docker host: http://host.docker.internal:4533/rest + extra_hosts: + - "host.docker.internal:host-gateway" + + db: + image: postgres:16-alpine + restart: unless-stopped + environment: + POSTGRES_USER: playlistd + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} + POSTGRES_DB: playlistd + volumes: + - db:/var/lib/postgresql/data + healthcheck: + test: ["CMD", "pg_isready", "-U", "playlistd", "-d", "playlistd"] + interval: 5s + timeout: 5s + retries: 20 + +volumes: + db: diff --git a/discover/.gitignore b/discover/.gitignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/discover/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/discover/index.html b/discover/index.html new file mode 100644 index 0000000..da6a5eb --- /dev/null +++ b/discover/index.html @@ -0,0 +1,13 @@ + + + + + + + Discover + + +
+ + + diff --git a/discover/package-lock.json b/discover/package-lock.json new file mode 100644 index 0000000..47a7bc5 --- /dev/null +++ b/discover/package-lock.json @@ -0,0 +1,1757 @@ +{ + "name": "playlistd-discover", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "playlistd-discover", + "version": "0.1.0", + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "@types/react": "18.3.12", + "@types/react-dom": "18.3.1", + "@vitejs/plugin-react": "4.3.3", + "typescript": "5.6.3", + "vite": "5.4.10" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.14.tgz", + "integrity": "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.14", + "@babel/types": "^7.29.14", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.14.tgz", + "integrity": "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.14.tgz", + "integrity": "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.14", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.14", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.3.tgz", + "integrity": "sha512-mqfypgH/liYjaSCoPI4erckUcROgZtmFUUmyOJ05oyayi/tVqOEYAzWP7ufqCoCT3xB31Fw4XIVO/jX42hYvKA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.3.tgz", + "integrity": "sha512-5tY+GC/1gpt79cKS2DQzu6iD824j6BmI4q5Zb6qftZ4kWqIQmvR3DD4eJ2Gclu6/nVMYDk2IVpqxypWOiAuWJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.3.tgz", + "integrity": "sha512-nDBcQ/o3PMmGxmAzGBJFn+n1rb83Va9WSdFIq1AHmlEF3tuibVsyJ3kG5x13r7VIy6WI8SvzCdHVNSlSDIdj8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.3.tgz", + "integrity": "sha512-dra5zl0QWKkIkaMgNDNPC19gkMlPAfAf41yWlkGztXMIvUQrX9XWZFQRw7abhH3nks+XZGQpybINAxT2pKdFew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.3.tgz", + "integrity": "sha512-xo5xeo/AjEB/ArzQjGn0JRDZuybZicQ5O3VPfko6ocH1li/qNrN4p5+R/WgjavzRz6UwAOaqsau7VvRQA6i6AA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.3.tgz", + "integrity": "sha512-zdckkcxHDEEKyDbC1t21DeaaiKGymxbkBU9c3zyfaaz+8N96ItJw4nmzHhZF+Mukgt906fnf2tsc90pVyStuHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.3.tgz", + "integrity": "sha512-9oXqI7g/ycEz7TyicdGBC4sL6PfWMXAx8u15f/nd7lYkCLJd8U8VdBfbpc4SSnRBU/e7aPALve3mhzasGDeCYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.3.tgz", + "integrity": "sha512-hbgT4NlaOELE3D5UUzSqF+OFgwz4Scvo2SQD9nZJUFjdIsg9Kg3FabQauUxkHKY9N5yjNXfXRRmiKNN4JpLmFA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.3.tgz", + "integrity": "sha512-yECcXZ/Bl+JVRhLFgld42rYrXgPdE0LtySGAmmmH6OtkaJM17A4cWG/eCzDymMVb52/jZjW0R54YrTHj4xXlSA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.3.tgz", + "integrity": "sha512-q4Q4/B7wyqM+TFqY5tJYQlaz5+ksGopcRmMeMdu4q6eaPK7N1PymTjIaH5LL32mMJBqIzpRof7BhlYLim5JgNQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.3.tgz", + "integrity": "sha512-Ich3TGl/7GqhQ6G6jVPzgGQGJjd3E5hECxSVanPYchy6Vwcq+WI8wG/gmEMilHNy+ZYCR6U8EN50EejG3TaIgw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.3.tgz", + "integrity": "sha512-URBmOhwv4Y0Hi5Hhxc3cmqZLtQlx55DOs5PUhhITDC3zu0qwAfhcNAFAIwAhOUdA6NFVEck07CNZX6cBEs1vTg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.3.tgz", + "integrity": "sha512-PTdJXuZplRyaE3ECArlbZubI2LlUHWm0oCipCexnE/8LM+L7qIqUiNbU0piBxt46EB5zxXX+cpmDvHX4Z3WwcQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.3.tgz", + "integrity": "sha512-IlSQPDExSm9YdtrWeZIHj87GPXI9lYygRvHVwQ1o9t91JHIiB2CihrvNIASpc/zI28atqm04jS3proaQuaJMww==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.3.tgz", + "integrity": "sha512-O2ssyDcBTZkH5v2P/9ZaXJreL0hCKvUA5UwuHn0jCKeMLKi4GhspZJ1I5FT5QsHtJ/dPx4pup7pg/Lw0emeY0Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.3.tgz", + "integrity": "sha512-fesqagxcnc87lH2+aBWne/tFCmQVIGH+YezjY1wQwbUODuTBBlhHoyxju6umwn8LnjHVanjpoeaQdLsXP8JQSQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.3.tgz", + "integrity": "sha512-WAjFDtLW3HjJ2RAytKoWdFwlK/hW8rJHrjhRZFw14nR+c9JN//WIlSBkyXUjEYCNOFs2sGLNutOEPQG4iVYHgA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.3.tgz", + "integrity": "sha512-+fZiTeHV/1fy/14dRqE4thjYwUOABL6qQjxElOEQg2oHLkCamO8dxhHphVgD4+pFxtVEUIWxsGVduPtwnAlvbg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.3.tgz", + "integrity": "sha512-pfn4Zd9Ic3lEaSwW3GsQhTIDd7929C+eiEkOutsSCT2IHD6rDLblwmMQkgeGOso0oDo9Jk/ERtFdtFr9ElLs+g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.3.tgz", + "integrity": "sha512-eUXzaeNQbKXKNqseL3g/usUqOPmRu+DbQsvwr9MXMdV+VQFUNb9bcWSNAAs/TRV95PCbFK46kLzHEOhFSzujsg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.3.tgz", + "integrity": "sha512-OiUclE7QDU4H/hr3ACRHhVGKWl+gNx+6Emignfq0hmNmzzTkZnT79wzB9NXKd0QH16S4t/wVqlAFBfC17nkZ5A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.3.tgz", + "integrity": "sha512-s6EclDWmk6zvIfk1yixgYthk7xHNx0xu5cEF5RDpS4IHNTpfswRX6xOXVG5cHF5xWn0B6EpDGARhPQ520KTlsA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.3.tgz", + "integrity": "sha512-G2xnmxGnU8XHLwtjnnXNRcLrub+Af3nm9VQ1QzL2aEiAL7woBdRgTCZBslJl8umA+YMqdEFpUh9kJB/Vyzk2wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.3.tgz", + "integrity": "sha512-Y/4tApNVrMUYWbAHsyRWJgwuuJOfhTNhA2B04Xpa6+G9btkPZ9kU3XagUKzPTwF3hg36NpQk748JsnoTVho67Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.3.tgz", + "integrity": "sha512-i2vH/OA5BcW+TdNg12ZTRC4rn+vILaPMP9CvHqnv+QEpMjBHGGNLo4k4EnEqzjYvTD6x1Xark9WhsQbH4bTzUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.3.tgz", + "integrity": "sha512-ADb1Uz2MNM0sxVpAlMNdQG16Hw4sgW1aqVL7NeqBMpcZeiHb192d7W6shZdMQs33D+w9ihDYBBPsYqqc4MlD8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.9.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.9.0.tgz", + "integrity": "sha512-vuyHg81vvWA1Z1ELfvLko2c8f34gyA0zaic0+Rllc5lbCnbSyuvb2Oxpm6TAUAC/2xZN3QGqxBNggD1nNR2AfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.8" + } + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.12", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.12.tgz", + "integrity": "sha512-D2wOSq/d6Agt28q7rSI3jhU7G6aiuzljDGZ2hTZHIkrTLUI+AF3WMeKkEZ9nN2fkBAlcktT6vcZjDFiIhMYEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-qW1Mfv8taImTthu4KoXgDfLuk4bydU6Q/TkADnDWWHwi4NX4BR+LWfTp2sVmTqRrsHvyDDTelgelxJ+SsejKKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.3.tgz", + "integrity": "sha512-NooDe9GpHGqNns1i8XDERg0Vsg5SSYRhRxxyTGogUdkdNt47jal+fbuYi+Yfq6pzRCKXyoPcWisfxE6RIM3GKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.25.2", + "@babel/plugin-transform-react-jsx-self": "^7.24.7", + "@babel/plugin-transform-react-jsx-source": "^7.24.7", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.14.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.37", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.37.tgz", + "integrity": "sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.485", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.485.tgz", + "integrity": "sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.64", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.64.tgz", + "integrity": "sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", + "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.3.tgz", + "integrity": "sha512-wd2gavj7CEQv52rdcVqfUupO/KPIKcoJKxyFWl4cOqYZGMQEOSijJRkliz0dRa7gpkj/h4TRqyWa+dJJi6T0OA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.3", + "@rollup/rollup-android-arm64": "4.68.3", + "@rollup/rollup-android-x64": "4.68.3", + "@rollup/rollup-darwin-arm64": "4.68.3", + "@rollup/rollup-darwin-x64": "4.68.3", + "@rollup/rollup-freebsd-arm64": "4.68.3", + "@rollup/rollup-freebsd-x64": "4.68.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.3", + "@rollup/rollup-linux-arm-musleabihf": "4.68.3", + "@rollup/rollup-linux-arm64-gnu": "4.68.3", + "@rollup/rollup-linux-arm64-musl": "4.68.3", + "@rollup/rollup-linux-loong64-gnu": "4.68.3", + "@rollup/rollup-linux-loong64-musl": "4.68.3", + "@rollup/rollup-linux-ppc64-gnu": "4.68.3", + "@rollup/rollup-linux-ppc64-musl": "4.68.3", + "@rollup/rollup-linux-riscv64-gnu": "4.68.3", + "@rollup/rollup-linux-riscv64-musl": "4.68.3", + "@rollup/rollup-linux-s390x-gnu": "4.68.3", + "@rollup/rollup-linux-x64-gnu": "4.68.3", + "@rollup/rollup-linux-x64-musl": "4.68.3", + "@rollup/rollup-openbsd-x64": "4.68.3", + "@rollup/rollup-openharmony-arm64": "4.68.3", + "@rollup/rollup-win32-arm64-msvc": "4.68.3", + "@rollup/rollup-win32-ia32-msvc": "4.68.3", + "@rollup/rollup-win32-x64-gnu": "4.68.3", + "@rollup/rollup-win32-x64-msvc": "4.68.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/typescript": { + "version": "5.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", + "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "5.4.10", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.10.tgz", + "integrity": "sha512-1hvaPshuPUtxeQ0hsVH3Mud0ZanOLwVTneA1EgbAM5LhaZEqyPWGRQ7BtaMvUrTDeEaC8pxtj6a6jku3x4z6SQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/discover/package.json b/discover/package.json new file mode 100644 index 0000000..960286c --- /dev/null +++ b/discover/package.json @@ -0,0 +1,23 @@ +{ + "name": "playlistd-discover", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "@types/react": "18.3.12", + "@types/react-dom": "18.3.1", + "@vitejs/plugin-react": "4.3.3", + "typescript": "5.6.3", + "vite": "5.4.10" + } +} diff --git a/discover/src/AccountView.tsx b/discover/src/AccountView.tsx new file mode 100644 index 0000000..350a36c --- /dev/null +++ b/discover/src/AccountView.tsx @@ -0,0 +1,130 @@ +import { FormEvent, useState } from "react"; +import { Account, authApi } from "./api"; +import * as Icon from "./icons"; + +export function AccountView(props: { + account: Account; + onChange: (account: Account) => void; + onLogout: () => void; + onToast: (message: string) => void; +}) { + const { account } = props; + const [token, setToken] = useState(""); + const [busy, setBusy] = useState<"save" | "remove" | "logout" | null>(null); + const [error, setError] = useState(null); + + const saveToken = async (value: string) => { + setBusy(value ? "save" : "remove"); + setError(null); + try { + const updated = await authApi.setListenbrainzToken(value); + props.onChange(updated); + setToken(""); + props.onToast( + updated.listenbrainz_user + ? `Saved the token for ${updated.listenbrainz_user}` + : "Removed the Listenbrainz token", + ); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } + }; + + const submit = (e: FormEvent) => { + e.preventDefault(); + void saveToken(token.trim()); + }; + + const logout = async () => { + setBusy("logout"); + try { + await authApi.logout(); + } catch { + // the session is gone from this browser either way + } + props.onLogout(); + }; + + return ( +
+
+

Account

+

{account.username}

+
+ +
+
+
+

Listenbrainz token

+

+ Lets playlistd find new songs for each mix's genres with LB Radio, on top of your + recommendations. Find yours at{" "} + + listenbrainz.org/settings + + . New songs are picked up the next time your mixes are rebuilt. +

+
+
+ +

+ {account.has_listenbrainz_token ? ( + <> +

+ +
+ + {error &&

{error}

} +
+ {account.has_listenbrainz_token && ( + + )} + +
+
+
+ +
+
+
+

Session

+

Logged in as {account.username} in this browser.

+
+ +
+
+
+ ); +} diff --git a/discover/src/App.tsx b/discover/src/App.tsx new file mode 100644 index 0000000..a359c48 --- /dev/null +++ b/discover/src/App.tsx @@ -0,0 +1,258 @@ +import { useCallback, useEffect, useState } from "react"; +import { Account, api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api"; +import { usePlayer } from "./usePlayer"; +import { MixView, hue } from "./MixView"; +import { LikedView } from "./LikedView"; +import { TrackedView } from "./TrackedView"; +import { AccountView } from "./AccountView"; +import { PlayerBar } from "./PlayerBar"; +import * as Icon from "./icons"; + +type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" } | { view: "account" }; + +function parseHash(): Route { + const [, view, id] = window.location.hash.split("/"); + if (view === "liked" || view === "tracked" || view === "account") return { view }; + return { view: "mix", id: id || undefined }; +} + +type Toast = { message: string; undo?: () => void }; + +function storedRule() { + try { + return localStorage.getItem("discover.rule"); + } catch { + return null; + } +} + +export function App(props: { + account: Account; + onAccountChange: (account: Account) => void; + onLogout: () => void; +}) { + const [rules, setRules] = useState(null); + const [ruleId, setRuleId] = useState(storedRule); + const [mixes, setMixes] = useState(null); + const [detail, setDetail] = useState(null); + const [liked, setLiked] = useState([]); + const [route, setRoute] = useState(parseHash); + const [error, setError] = useState(null); + const [toast, setToast] = useState(null); + + const player = usePlayer((item) => setToast({ message: `Couldn't play “${item.title}”` })); + const rule = rules?.find((r) => r.id === ruleId) ?? rules?.[0]; + + useEffect(() => { + const onHash = () => setRoute(parseHash()); + window.addEventListener("hashchange", onHash); + return () => window.removeEventListener("hashchange", onHash); + }, []); + + useEffect(() => { + if (!toast) return; + const t = window.setTimeout(() => setToast(null), toast.undo ? 6000 : 3500); + return () => window.clearTimeout(t); + }, [toast]); + + const loadRules = useCallback(() => { + api.rules().then(setRules, (e) => setError(`Couldn't reach playlistd (${e.message})`)); + }, []); + useEffect(loadRules, [loadRules]); + + const loadMixes = useCallback(() => { + if (!rule) return; + api.mixes(rule.id).then(setMixes, (e) => setError(e.message)); + api.liked(rule.id).then(setLiked, () => undefined); + }, [rule?.id]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(loadMixes, [loadMixes]); + + // mixes are built by the daemon; check back while they're pending + const pending = !!rule && (!rule.last_run || mixes?.length === 0); + useEffect(() => { + if (!pending) return; + const t = window.setInterval(() => { + loadRules(); + loadMixes(); + }, 10000); + return () => window.clearInterval(t); + }, [pending, loadRules, loadMixes]); + + const mixId = route.view === "mix" ? route.id ?? mixes?.[0]?.id : undefined; + const loadDetail = useCallback( + (quiet = false) => { + if (!mixId) return; + if (!quiet) setDetail((d) => (d?.id === mixId ? d : null)); + api.mix(mixId).then(setDetail, (e) => !quiet && setError(`Couldn't load mix (${e.message})`)); + }, + [mixId], + ); + useEffect(() => loadDetail(), [loadDetail]); + + // pick up YouTube links once a new song has been found and starts playing + useEffect(() => { + if (player.status === "playing" && player.current?.source === "youtube") { + loadDetail(true); + if (rule) api.liked(rule.id).then(setLiked, () => undefined); + } + }, [player.status, player.current?.key]); // eslint-disable-line react-hooks/exhaustive-deps + + const updateLocal = (id: string, status: SuggestionStatus, previous?: Suggestion) => { + setDetail((d) => { + if (!d) return d; + const suggestions = + status === "dismissed" + ? d.suggestions.filter((s) => s.id !== id) + : d.suggestions.some((s) => s.id === id) + ? d.suggestions.map((s) => (s.id === id ? { ...s, status } : s)) + : previous && previous.mix_id === d.id + ? [...d.suggestions, { ...previous, status }].sort((a, b) => b.score - a.score) + : d.suggestions; + return { ...d, suggestions }; + }); + setLiked((l) => { + const without = l.filter((s) => s.id !== id); + const item = previous ?? l.find((s) => s.id === id); + return status === "liked" && item ? [{ ...item, status }, ...without] : without; + }); + }; + + const onStatus = (s: Suggestion, status: SuggestionStatus) => { + updateLocal(s.id, status, s); + api.setStatus(s.id, status).then( + () => { + loadMixes(); + if (status === "dismissed") { + setToast({ + message: `Hid “${s.title}”`, + undo: () => { + updateLocal(s.id, s.status, s); + api.setStatus(s.id, s.status).then(loadMixes); + setToast(null); + }, + }); + } + }, + () => { + updateLocal(s.id, s.status, s); + setToast({ message: "Couldn't save that, try again" }); + }, + ); + }; + + const rebuild = () => { + if (!rule) return; + api.rebuild(rule.id).then(() => { + setToast({ message: "Rebuilding mixes. This takes a minute or two." }); + loadRules(); + }); + }; + + return ( +
+ + +
+ {error &&
{error}
} + {(route.view === "mix" || route.view === "liked") && rules && rules.length === 0 && ( +
+

No mix rules yet

+

Create one, and playlistd will cluster your listens into genre mixes:

+
{`curl -c cookies -X POST ${location.origin}/api/auth/login -H 'Content-Type: application/json' \\\n  -d '{"username": "${props.account.username}", "password": "…"}'\ncurl -b cookies -X POST ${location.origin}/api/playlist/mix -H 'Content-Type: application/json' \\\n  -d '{"tracking_user": "your-listenbrainz-name"}'`}
+
+ )} + {(route.view === "mix" || route.view === "liked") && pending && mixes?.length === 0 && ( +
Building mixes from your recent listens…
+ )} + {route.view === "account" ? ( + setToast({ message })} + /> + ) : route.view === "tracked" ? ( + setToast({ message })} /> + ) : route.view === "liked" ? ( + + ) : detail ? ( + + ) : ( + mixId &&
Loading…
+ )} +
+ + + + {toast && ( +
+ {toast.message} + {toast.undo && } +
+ )} +
+ ); +} diff --git a/discover/src/Auth.tsx b/discover/src/Auth.tsx new file mode 100644 index 0000000..2adcbae --- /dev/null +++ b/discover/src/Auth.tsx @@ -0,0 +1,166 @@ +import { FormEvent, useCallback, useEffect, useState } from "react"; +import { Account, authApi, UNAUTHORIZED_EVENT } from "./api"; +import { App } from "./App"; +import * as Icon from "./icons"; + +type State = + | { kind: "loading" } + | { kind: "unreachable"; message: string } + | { kind: "setup" } + | { kind: "login"; expired?: boolean } + | { kind: "ready"; account: Account }; + +/** Shows the app once logged in. The first visit creates the account instead. */ +export function AuthGate() { + const [state, setState] = useState({ kind: "loading" }); + + const check = useCallback(() => { + authApi.status().then( + (s) => + setState( + s.account + ? { kind: "ready", account: s.account } + : s.setup_required + ? { kind: "setup" } + : { kind: "login" }, + ), + (e) => setState({ kind: "unreachable", message: e.message }), + ); + }, []); + useEffect(check, [check]); + + // the session ran out (or was logged out elsewhere) while using the app + useEffect(() => { + const onUnauthorized = () => + setState((s) => (s.kind === "ready" ? { kind: "login", expired: true } : s)); + window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized); + return () => window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized); + }, []); + + switch (state.kind) { + case "loading": + return
; + case "unreachable": + return ( +
+
+ Couldn't reach playlistd ({state.message}) + +
+
+ ); + case "setup": + case "login": + return ( + setState({ kind: "ready", account })} + // someone else finished setting up first + onRecheck={check} + /> + ); + case "ready": + return ( + setState({ kind: "ready", account })} + onLogout={() => setState({ kind: "login" })} + /> + ); + } +} + +function CredentialsForm(props: { + setup: boolean; + expired?: boolean; + onDone: (account: Account) => void; + onRecheck: () => void; +}) { + const { setup } = props; + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [confirm, setConfirm] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const submit = async (e: FormEvent) => { + e.preventDefault(); + if (setup && password !== confirm) { + setError("The passwords don't match"); + return; + } + setBusy(true); + setError(null); + try { + props.onDone(setup ? await authApi.setup(username, password) : await authApi.login(username, password)); + } catch (err) { + setError((err as Error).message); + setBusy(false); + if (setup) props.onRecheck(); + } + }; + + return ( +
+
+
+ + playlistd +
+
+

{setup ? "Create your account" : "Log in"}

+

+ {setup + ? "Choose the username and password you'll use to log in to playlistd from now on." + : props.expired + ? "Your session has ended. Log in again to continue." + : "Log in to continue."} +

+
+ + + {setup && ( + + )} + {error &&

{error}

} + +
+
+ ); +} diff --git a/discover/src/LikedView.tsx b/discover/src/LikedView.tsx new file mode 100644 index 0000000..41e0b71 --- /dev/null +++ b/discover/src/LikedView.tsx @@ -0,0 +1,47 @@ +import { useMemo } from "react"; +import { Suggestion, SuggestionStatus } from "./api"; +import { fromSuggestion } from "./queue"; +import { Player } from "./usePlayer"; +import { TrackRow } from "./TrackRow"; +import { SuggestionActions } from "./MixView"; +import * as Icon from "./icons"; + +type Props = { + liked: Suggestion[]; + player: Player; + onStatus: (s: Suggestion, status: SuggestionStatus) => void; +}; + +export function LikedView({ liked, player, onStatus }: Props) { + const items = useMemo(() => liked.map(fromSuggestion), [liked]); + return ( +
+
+ +
+

Collection

+

Liked new songs

+

Songs you liked that aren't in your library yet: a shopping list.

+
+ +
+
+
+
+ {items.length === 0 ? ( +

Nothing yet. Tap the heart on a new song to keep it here.

+ ) : ( +
    + {liked.map((s, i) => ( + player.playAt(items, i)} + actions={} /> + ))} +
+ )} +
+
+ ); +} diff --git a/discover/src/MixView.tsx b/discover/src/MixView.tsx new file mode 100644 index 0000000..f5ae245 --- /dev/null +++ b/discover/src/MixView.tsx @@ -0,0 +1,134 @@ +import { useMemo } from "react"; +import { MixDetail, mixTitle, Suggestion, SuggestionStatus } from "./api"; +import { fromSong, fromSuggestion, mixAtRatio, QueueItem, shuffled } from "./queue"; +import { Player } from "./usePlayer"; +import { TrackRow } from "./TrackRow"; +import * as Icon from "./icons"; + +export function hue(text: string) { + let h = 0; + for (const c of text) h = (h * 31 + c.charCodeAt(0)) % 360; + return h; +} + +export function SuggestionActions({ s, onStatus }: { s: Suggestion; onStatus: (s: Suggestion, status: SuggestionStatus) => void }) { + const liked = s.status === "liked"; + return ( + <> + + {s.youtube_id ? ( + + ) : ( + + )} + {s.status !== "liked" && ( + + )} + + ); +} + +type Props = { + mix: MixDetail; + /** Share of "Play mix" made of songs the user already knows */ + knownRatio: number; + player: Player; + onStatus: (s: Suggestion, status: SuggestionStatus) => void; +}; + +export function MixView({ mix, knownRatio, player, onStatus }: Props) { + const fresh = useMemo(() => mix.suggestions.map(fromSuggestion), [mix.suggestions]); + const library = useMemo(() => mix.songs.map(fromSong), [mix.songs]); + const knownIds = useMemo(() => new Set(mix.known_song_ids), [mix.known_song_ids]); + // mixes built before songs were marked as known fall back to the whole library + const known = useMemo( + () => (knownIds.size ? library.filter((_, i) => knownIds.has(mix.songs[i].id)) : library), + [library, knownIds, mix.songs], + ); + // clicking a new song plays the new songs in order, with known songs mixed in + const mixed = useMemo(() => mixAtRatio(fresh, known, knownRatio), [fresh, known, knownRatio]); + const percent = Math.round(Math.min(Math.max(knownRatio, 0), 1) * 100); + const title = mixTitle(mix); + const h = hue(mix.tags.join()); + + const play = (items: QueueItem[], at = 0) => items.length && player.playAt(items, at); + const isActive = (item: QueueItem) => player.current?.key === item.key; + + return ( +
+
+ +
+

Mix

+

{title}

+
    + {mix.tags.map((t) =>
  • {t}
  • )} +
+

+ {mix.suggestions.length} new · {mix.songs.length} from your library + {knownIds.size > 0 && <>, {knownIds.size} you've played} +

+
+ + +
+
+
+ +
+

New for you

+ {fresh.length === 0 ? ( +

No new songs for this mix yet. They're found when the mixes are rebuilt.

+ ) : ( +
    + {mix.suggestions.map((s, i) => ( + play(mixed, mixed.indexOf(fresh[i]))} + meta={{Math.round(s.score * 100)}% match} + actions={} + /> + ))} +
+ )} +
+ +
+

From your library

+
    + {mix.songs.map((song, i) => ( + play(library, i)} + duration={song.duration} + meta={knownIds.has(song.id) ? Played : undefined} + /> + ))} +
+
+
+ ); +} diff --git a/discover/src/PlayerBar.tsx b/discover/src/PlayerBar.tsx new file mode 100644 index 0000000..0be9a1e --- /dev/null +++ b/discover/src/PlayerBar.tsx @@ -0,0 +1,55 @@ +import { Player } from "./usePlayer"; +import { Cover, formatTime } from "./TrackRow"; +import * as Icon from "./icons"; + +export function PlayerBar({ player }: { player: Player }) { + const { current, status, time, duration } = player; + if (!current) return null; + const label = + status === "loading" + ? current.source === "youtube" ? "Finding on YouTube…" : "Loading…" + : status === "error" ? "Couldn't play this one, skipping" : null; + + return ( +
+
+ +
+
{current.title}
+
{current.artist}
+
+ + {current.source === "youtube" ? "YouTube" : "Library"} + +
+
+
+ + + +
+
+ {formatTime(time) || "0:00"} + player.seek(Number(e.target.value))} + aria-label="Seek" + style={{ ["--progress" as string]: `${duration ? (time / duration) * 100 : 0}%` }} + /> + {formatTime(duration)} +
+ {label &&
{label}
} +
+
+ {player.index + 1} / {player.queue.length} +
+
+ ); +} diff --git a/discover/src/TrackRow.tsx b/discover/src/TrackRow.tsx new file mode 100644 index 0000000..5602d2a --- /dev/null +++ b/discover/src/TrackRow.tsx @@ -0,0 +1,56 @@ +import { ReactNode } from "react"; +import { QueueItem } from "./queue"; +import { PlayerStatus } from "./usePlayer"; +import * as Icon from "./icons"; + +export function formatTime(seconds?: number) { + if (!seconds || !Number.isFinite(seconds)) return ""; + const s = Math.floor(seconds); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +} + +export function Cover({ src, label, size = 44 }: { src?: string | null; label: string; size?: number }) { + return ( + + ); +} + +type Props = { + item: QueueItem; + number: number; + active: boolean; + status: PlayerStatus; + onPlay: () => void; + meta?: ReactNode; + actions?: ReactNode; + duration?: number; +}; + +export function TrackRow({ item, number, active, status, onPlay, meta, actions, duration }: Props) { + const loading = active && status === "loading"; + const playing = active && status === "playing"; + return ( +
  • + + +
    +
    {item.title}
    +
    + {item.artist} + {item.album && · {item.album}} +
    +
    + {meta &&
    {meta}
    } +
    {formatTime(duration)}
    + {actions &&
    {actions}
    } +
  • + ); +} diff --git a/discover/src/TrackedView.tsx b/discover/src/TrackedView.tsx new file mode 100644 index 0000000..29d5225 --- /dev/null +++ b/discover/src/TrackedView.tsx @@ -0,0 +1,522 @@ +import { FormEvent, ReactNode, useCallback, useEffect, useMemo, useState } from "react"; +import { + PERIODS, + periodLabel, + SubsonicPlaylist, + TrackedPlaylist, + TrackedRule, + trackedApi, + Tracking, +} from "./api"; +import * as Icon from "./icons"; + +type Props = { + /** Listenbrainz user to suggest for new playlists */ + defaultUser?: string; + onToast: (message: string) => void; +}; + +const describe = (t: Tracking) => `Top ${t.playlist_size} · ${periodLabel(t.tracking_type)} · ${t.tracking_user}`; + +export function TrackedView({ defaultUser, onToast }: Props) { + const [playlists, setPlaylists] = useState(null); + const [rules, setRules] = useState(null); + const [error, setError] = useState(null); + // "new-playlist", "new-rule", or the id of the item being edited + const [editing, setEditing] = useState(null); + const [confirming, setConfirming] = useState(null); + const [refreshing, setRefreshing] = useState>(new Set()); + + const load = useCallback(() => { + trackedApi.playlists().then(setPlaylists, (e) => setError(e.message)); + trackedApi.rules().then(setRules, (e) => setError(e.message)); + }, []); + useEffect(load, [load]); + + const users = useMemo(() => { + const all = [defaultUser, ...(playlists ?? []).map((p) => p.tracking_user), ...(rules ?? []).map((r) => r.tracking_user)]; + return [...new Set(all.filter((u): u is string => !!u))]; + }, [defaultUser, playlists, rules]); + const suggestedUser = users[0] ?? ""; + + const replace = (items: T[] | null, item: T) => + items?.some((i) => i.id === item.id) ? items.map((i) => (i.id === item.id ? item : i)) : [...(items ?? []), item]; + + const refresh = async (p: TrackedPlaylist) => { + setRefreshing((s) => new Set(s).add(p.id)); + try { + const updated = await trackedApi.refresh(p.id); + setPlaylists((ps) => replace(ps, updated)); + const found = updated.song_count ?? 0; + onToast( + found < updated.playlist_size + ? `Updated “${updated.name ?? "playlist"}”: ${found} of the top ${updated.playlist_size} are in your library` + : `Updated “${updated.name ?? "playlist"}” with ${found} songs`, + ); + } catch (e) { + onToast((e as Error).message); + } finally { + setRefreshing((s) => { + const next = new Set(s); + next.delete(p.id); + return next; + }); + } + }; + + return ( +
    +
    +

    Manage

    +

    Tracked playlists

    +

    + Subsonic playlists kept up to date with your top songs on Listenbrainz. +

    +
    + {error &&
    {error}
    } + +
    +
    +
    +

    Playlists

    +

    Refreshed automatically every few minutes.

    +
    + {editing !== "new-playlist" && ( + + )} +
    + + {editing === "new-playlist" && ( + setEditing(null)} + onSaved={(p) => { + setPlaylists((ps) => replace(ps, p)); + setEditing(null); + onToast(`Tracking “${p.name}”. Refreshing it now…`); + void refresh(p); + }} + /> + )} + + {playlists === null ? ( +

    Loading…

    + ) : playlists.length === 0 && editing !== "new-playlist" ? ( +

    No tracked playlists yet. Create one to keep, say, your top 50 of the last month in Subsonic.

    + ) : ( +
      + {playlists.map((p) => + editing === p.id ? ( +
    • + setEditing(null)} + onSaved={(updated) => { + setPlaylists((ps) => replace(ps, updated)); + setEditing(null); + onToast("Saved. Refresh to apply the changes now."); + }} + /> +
    • + ) : ( + : } + title={p.name ?? Missing from Subsonic} + subtitle={describe(p)} + aside={ + p.song_count === null ? undefined : p.song_count > 0 && p.song_count < p.playlist_size ? ( + + {p.song_count} of {p.playlist_size} found + + ) : ( + `${p.song_count} songs` + ) + } + actions={ + <> + + + + + } + confirm={ + confirming === p.id && ( + setConfirming(null)} + onRemoved={(deleted) => { + setPlaylists((ps) => ps?.filter((x) => x.id !== p.id) ?? null); + setConfirming(null); + onToast(deleted ? "Playlist deleted" : "Stopped tracking. The playlist stays in Subsonic."); + }} + /> + ) + } + /> + ), + )} +
    + )} +
    + +
    +
    +
    +

    Recurring playlists

    +

    Start a new tracked playlist whenever the name changes, e.g. each year or month.

    +
    + {editing !== "new-rule" && ( + + )} +
    + + {editing === "new-rule" && ( + setEditing(null)} + onSaved={(r) => { + setRules((rs) => replace(rs, r)); + setEditing(null); + onToast(`“${r.current_name}” will be created within a few minutes`); + // the daemon creates the playlist; show it once it's there + window.setTimeout(load, 15000); + }} + /> + )} + + {rules === null ? ( +

    Loading…

    + ) : rules.length === 0 && editing !== "new-rule" ? ( +

    No recurring playlists. A rule like “%Y - Top 100” makes a new top 100 every year.

    + ) : ( +
      + {rules.map((r) => + editing === r.id ? ( +
    • + setEditing(null)} + onSaved={(updated) => { + setRules((rs) => replace(rs, updated)); + setEditing(null); + onToast("Saved. Applies to playlists the rule makes from now on."); + }} + /> +
    • + ) : ( + } + title={{r.name_template}} + subtitle={describe(r)} + aside={ + r.last_name && r.last_name === r.current_name + ? <>Current: {r.last_name} + : r.current_name ? <>Next: {r.current_name} : undefined + } + actions={ + <> + + + + } + confirm={ + confirming === r.id && ( + setConfirming(null)} + onConfirm={async () => { + await trackedApi.removeRule(r.id); + setRules((rs) => rs?.filter((x) => x.id !== r.id) ?? null); + setConfirming(null); + }} + /> + ) + } + /> + ), + )} +
    + )} +
    +
    + ); +} + +function Item(props: { icon: ReactNode; title: ReactNode; subtitle: string; aside?: ReactNode; actions: ReactNode; confirm?: ReactNode }) { + return ( +
  • +
    + +
    +
    {props.title}
    +
    {props.subtitle}
    +
    + {props.aside &&
    {props.aside}
    } +
    {props.actions}
    +
    + {props.confirm} +
  • + ); +} + +function Confirm(props: { message: ReactNode; action: string; onCancel: () => void; onConfirm: () => Promise; children?: ReactNode }) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + return ( +
    +

    {props.message}

    + {props.children} + {error &&

    {error}

    } +
    + + +
    +
    + ); +} + +function RemovePlaylist(props: { playlist: TrackedPlaylist; onCancel: () => void; onRemoved: (deleted: boolean) => void }) { + const [alsoDelete, setAlsoDelete] = useState(false); + return ( + Stop updating “{props.playlist.name ?? "this playlist"}”?} + action={alsoDelete ? "Delete playlist" : "Stop tracking"} + onCancel={props.onCancel} + onConfirm={async () => { + await trackedApi.remove(props.playlist.id, alsoDelete); + props.onRemoved(alsoDelete); + }} + > + {props.playlist.name && ( + + )} + + ); +} + +/** Fields shared by playlists and rules */ +function TrackingFields({ value, onChange, users }: { value: Tracking; onChange: (t: Tracking) => void; users: string[] }) { + return ( + <> + + + + + ); +} + +function useSubmit(save: () => Promise, onSaved: (t: T) => void) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const submit = async (e: FormEvent) => { + e.preventDefault(); + setBusy(true); + setError(null); + try { + onSaved(await save()); + } catch (err) { + setError((err as Error).message); + setBusy(false); + } + }; + return { busy, error, submit }; +} + +function PlaylistForm(props: { + initial: Tracking & Partial; + users: string[]; + onCancel: () => void; + onSaved: (p: TrackedPlaylist) => void; +}) { + const creating = !props.initial.id; + const [tracking, setTracking] = useState({ + playlist_size: props.initial.playlist_size, + tracking_user: props.initial.tracking_user, + tracking_type: props.initial.tracking_type, + }); + const [mode, setMode] = useState<"new" | "existing">("new"); + const [name, setName] = useState(props.initial.name ?? ""); + const [existingId, setExistingId] = useState(""); + const [subsonic, setSubsonic] = useState(null); + + useEffect(() => { + if (creating && mode === "existing" && subsonic === null) { + trackedApi.subsonicPlaylists().then(setSubsonic, () => setSubsonic([])); + } + }, [creating, mode, subsonic]); + const available = subsonic?.filter((p) => !p.tracked) ?? []; + + const { busy, error, submit } = useSubmit( + () => + creating + ? trackedApi.create(mode === "new" ? { ...tracking, name } : { ...tracking, playlist_id: existingId }) + : trackedApi.update(props.initial.id!, { ...tracking, name: name || undefined }), + props.onSaved, + ); + + return ( +
    + {creating && ( +
    + + +
    + )} +
    + {creating && mode === "existing" ? ( +
    + + + Its songs will be replaced with your top songs. +
    + ) : ( + (creating || props.initial.name) && ( + + ) + )} + +
    + {error &&

    {error}

    } +
    + + +
    +
    + ); +} + +function RuleForm(props: { + initial: Tracking & { name_template: string; id?: string }; + users: string[]; + onCancel: () => void; + onSaved: (r: TrackedRule) => void; +}) { + const creating = !props.initial.id; + const [tracking, setTracking] = useState({ + playlist_size: props.initial.playlist_size, + tracking_user: props.initial.tracking_user, + tracking_type: props.initial.tracking_type, + }); + const [template, setTemplate] = useState(props.initial.name_template); + const [preview, setPreview] = useState<{ name?: string; error?: string }>({}); + + useEffect(() => { + const t = window.setTimeout(() => { + trackedApi.previewName(template).then( + ({ name }) => setPreview({ name }), + (e) => setPreview({ error: e.message }), + ); + }, 250); + return () => window.clearTimeout(t); + }, [template]); + + const { busy, error, submit } = useSubmit( + () => + creating + ? trackedApi.createRule({ ...tracking, name_template: template }) + : trackedApi.updateRule(props.initial.id!, { ...tracking, name_template: template }), + props.onSaved, + ); + + return ( +
    +
    +
    + + setTemplate(e.target.value)} spellCheck={false} + aria-describedby="template-help" className="mono" /> + + {preview.error ? ( + {preview.error} + ) : preview.name ? ( + <>Today this makes {preview.name}. + ) : null} + Use %Y for the year, %B the month, %m its number, %V the week. A new playlist starts whenever the name changes. + +
    + +
    + {error &&

    {error}

    } +
    + + +
    +
    + ); +} diff --git a/discover/src/api.ts b/discover/src/api.ts new file mode 100644 index 0000000..d7cc81c --- /dev/null +++ b/discover/src/api.ts @@ -0,0 +1,184 @@ +export type Rule = { + id: string; + tracking_user: string; + months: number; + playlist_size: number; + discovery_count: number; + /** Share of a mix made of songs the user already knows */ + familiar_ratio: number; + last_run: string | null; +}; + +export type MixSummary = { + id: string; + playlist_id: string; + name: string | null; + tags: string[]; + position: number; + new_count: number; +}; + +export type Song = { + id: string; + title: string; + artist: string; + album: string; + duration?: number; + coverArt?: string; +}; + +export type SuggestionStatus = "new" | "liked" | "dismissed"; + +export type Suggestion = { + id: string; + mix_id: string | null; + recording_mbid: string; + title: string; + artist: string; + release: string | null; + cover_url: string | null; + score: number; + status: SuggestionStatus; + youtube_id: string | null; +}; + +export type MixDetail = MixSummary & { + songs: Song[]; + /** Songs in `songs` the user played recently */ + known_song_ids: string[]; + suggestions: Suggestion[]; +}; + +/** Fired when the API says the session has ended, so the app can ask to log in again */ +export const UNAUTHORIZED_EVENT = "playlistd:unauthorized"; + +async function request(path: string, init?: RequestInit, base = "/api/discover"): Promise { + const response = await fetch(`${base}${path}`, init); + if (!response.ok) { + // (a failed login is just a wrong password) + if (response.status === 401 && `${base}${path}` !== "/api/auth/login") { + window.dispatchEvent(new Event(UNAUTHORIZED_EVENT)); + } + // the API explains what went wrong where it can + const body = await response.json().catch(() => null); + throw new Error(body?.error ?? `${response.status} ${response.statusText}`); + } + const text = await response.text(); + return text ? JSON.parse(text) : (undefined as T); +} + +const json = (method: string, body: unknown): RequestInit => ({ + method, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), +}); + +export const api = { + rules: () => request("/rules"), + mixes: (ruleId: string) => request(`/rules/${ruleId}/mixes`), + mix: (mixId: string) => request(`/mixes/${mixId}`), + liked: (ruleId: string) => request(`/rules/${ruleId}/liked`), + setStatus: (id: string, status: SuggestionStatus) => + request(`/suggestions/${id}`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ status }), + }), + rebuild: (ruleId: string) => request(`/rules/${ruleId}/rebuild`, { method: "POST" }), +}; + +export const coverUrl = (coverArt: string, size = 120) => + `/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`; +export const streamUrl = (songId: string) => `/api/discover/stream/${encodeURIComponent(songId)}`; +export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${suggestionId}`; + +/** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */ +export const mixTitle = (mix: MixSummary) => + (mix.name ?? mix.tags.join(" / ")).replace(/^mix:\s*/i, ""); + +// ---------- tracked playlists ---------- + +export const PERIODS: [string, string][] = [ + ["this_week", "This week so far"], + ["this_month", "This month so far"], + ["this_year", "This year so far"], + ["week", "Last week"], + ["month", "Last month"], + ["quarter", "Last quarter"], + ["half_yearly", "Last six months"], + ["year", "Last year"], + ["all_time", "All time"], +]; + +export const periodLabel = (period: string) => + PERIODS.find(([value]) => value === period)?.[1] ?? period; + +export type Tracking = { + playlist_size: number; + tracking_user: string; + tracking_type: string; +}; + +export type TrackedPlaylist = Tracking & { + id: string; + playlist_id: string | null; + /** null when the playlist no longer exists in Subsonic */ + name: string | null; + song_count: number | null; +}; + +export type TrackedRule = Tracking & { + id: string; + name_template: string; + last_name: string | null; + current_name: string | null; +}; + +export type SubsonicPlaylist = { id: string; name: string; song_count: number; tracked: boolean }; + +const tracked = (path: string, init?: RequestInit) => request(path, init, "/api/tracked"); + +export const trackedApi = { + playlists: () => tracked("/playlists"), + create: (body: Tracking & { name?: string; playlist_id?: string }) => + tracked("/playlists", json("POST", body)), + update: (id: string, body: Tracking & { name?: string }) => + tracked(`/playlists/${id}`, json("PUT", body)), + remove: (id: string, deletePlaylist: boolean) => + tracked(`/playlists/${id}?delete_playlist=${deletePlaylist}`, { method: "DELETE" }), + refresh: (id: string) => tracked(`/playlists/${id}/refresh`, { method: "POST" }), + subsonicPlaylists: () => tracked("/subsonic-playlists"), + rules: () => tracked("/rules"), + createRule: (body: Tracking & { name_template: string }) => tracked("/rules", json("POST", body)), + updateRule: (id: string, body: Tracking & { name_template: string }) => + tracked(`/rules/${id}`, json("PUT", body)), + removeRule: (id: string) => tracked(`/rules/${id}`, { method: "DELETE" }), + previewName: (template: string) => + tracked<{ name: string }>(`/preview-name?template=${encodeURIComponent(template)}`), +}; + +// ---------- account ---------- + +export type Account = { + username: string; + /** The Listenbrainz user the saved token belongs to */ + listenbrainz_user: string | null; + has_listenbrainz_token: boolean; +}; + +export type AuthStatus = { + /** No account exists yet: the first visit creates it */ + setup_required: boolean; + account: Account | null; +}; + +const auth = (path: string, init?: RequestInit) => request(path, init, "/api/auth"); + +export const authApi = { + status: () => auth("/status"), + setup: (username: string, password: string) => auth("/setup", json("POST", { username, password })), + login: (username: string, password: string) => auth("/login", json("POST", { username, password })), + logout: () => auth("/logout", { method: "POST" }), + /** An empty token removes the saved one */ + setListenbrainzToken: (token: string) => auth("/account/listenbrainz", json("PUT", { token })), +}; diff --git a/discover/src/icons.tsx b/discover/src/icons.tsx new file mode 100644 index 0000000..7370538 --- /dev/null +++ b/discover/src/icons.tsx @@ -0,0 +1,23 @@ +type P = { size?: number }; +const svg = (path: JSX.Element, size = 18) => ( + +); +export const Play = ({ size }: P) => svg(, size); +export const Pause = ({ size }: P) => svg(<>, size); +export const Next = ({ size }: P) => svg(<>, size); +export const Prev = ({ size }: P) => svg(<>, size); +export const Heart = ({ size, filled }: P & { filled?: boolean }) => svg(, size); +export const Close = ({ size }: P) => svg(, size); +export const External = ({ size }: P) => svg(<>, size); +export const Refresh = ({ size }: P) => svg(<>, size); +export const Sparkle = ({ size }: P) => svg(, size); +export const Library = ({ size }: P) => svg(<>, size); +export const Shuffle = ({ size }: P) => svg(<>, size); +export const Plus = ({ size }: P) => svg(, size); +export const Pencil = ({ size }: P) => svg(<>, size); +export const Trash = ({ size }: P) => svg(<>, size); +export const ListMusic = ({ size }: P) => svg(<>, size); +export const Calendar = ({ size }: P) => svg(<>, size); +export const Warning = ({ size }: P) => svg(<>, size); +export const User = ({ size }: P) => svg(<>, size); diff --git a/discover/src/main.tsx b/discover/src/main.tsx new file mode 100644 index 0000000..bff1f88 --- /dev/null +++ b/discover/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { AuthGate } from "./Auth"; +import "./styles.css"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/discover/src/queue.ts b/discover/src/queue.ts new file mode 100644 index 0000000..464cbc4 --- /dev/null +++ b/discover/src/queue.ts @@ -0,0 +1,62 @@ +import { coverUrl, Song, streamUrl, Suggestion, youtubeUrl } from "./api"; + +export type QueueItem = { + key: string; + source: "library" | "youtube"; + src: string; + title: string; + artist: string; + album?: string | null; + cover?: string | null; + suggestionId?: string; +}; + +export const fromSong = (song: Song): QueueItem => ({ + key: `song:${song.id}`, + source: "library", + src: streamUrl(song.id), + title: song.title, + artist: song.artist, + album: song.album, + cover: song.coverArt ? coverUrl(song.coverArt, 300) : null, +}); + +export const fromSuggestion = (s: Suggestion): QueueItem => ({ + key: `suggestion:${s.id}`, + source: "youtube", + src: youtubeUrl(s.id), + title: s.title, + artist: s.artist, + album: s.release, + cover: s.cover_url, + suggestionId: s.id, +}); + +/** + * Mix known songs into new ones so that `ratio` of the result is known songs, spread evenly. + * If there aren't enough known songs to keep the ratio, all of them are used. + */ +export function mixAtRatio(fresh: QueueItem[], known: QueueItem[], ratio: number): QueueItem[] { + const r = Math.min(Math.max(ratio, 0), 1); + const wanted = r >= 1 ? known.length : Math.round((fresh.length * r) / (1 - r)); + const k = Math.min(wanted, known.length); + const total = fresh.length + k; + const out: QueueItem[] = []; + let f = 0; + let n = 0; + for (let i = 0; i < total; i++) { + // a known song wherever the running count of known songs steps up + const isKnown = Math.floor(((i + 1) * k) / total) > Math.floor((i * k) / total); + out.push(isKnown ? known[n++] : fresh[f++]); + } + return out; +} + +export function shuffled(items: T[]): T[] { + const out = [...items]; + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [out[i], out[j]] = [out[j], out[i]]; + } + return out; +} diff --git a/discover/src/styles.css b/discover/src/styles.css new file mode 100644 index 0000000..c45c47f --- /dev/null +++ b/discover/src/styles.css @@ -0,0 +1,1219 @@ +:root { + --bg: #f6f5f2; + --surface: #ffffff; + --surface-2: #efede8; + --border: #e2dfd8; + --text: #1d1b18; + --muted: #6d675e; + --accent: #5b3df5; + --accent-text: #ffffff; + --youtube: #d4351c; + --library: #2f7d4f; + --heart: #e0245e; + --shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%); + --art-l: 62%; + --art-s: 70%; + --radius: 12px; + font-family: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + font-size: 15px; + line-height: 1.45; + color: var(--text); + background: var(--bg); + -webkit-font-smoothing: antialiased; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #121214; + --surface: #1b1b1f; + --surface-2: #26262b; + --border: #2e2e34; + --text: #f1f0ee; + --muted: #a09d98; + --accent: #8b74ff; + --accent-text: #120d26; + --youtube: #ff6b52; + --library: #5fcf8d; + --heart: #ff5c8a; + --shadow: 0 1px 2px rgb(0 0 0 / 30%), 0 8px 24px rgb(0 0 0 / 30%); + --art-l: 45%; + --art-s: 55%; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--bg); +} + +button, +select, +input { + font: inherit; + color: inherit; +} + +a { + color: inherit; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +/* ---------- layout ---------- */ + +.app { + display: grid; + grid-template-columns: 272px minmax(0, 1fr); + min-height: 100vh; +} + +.sidebar { + position: sticky; + top: 0; + height: 100vh; + overflow-y: auto; + padding: 20px 12px; + border-right: 1px solid var(--border); + background: var(--surface); +} + +.with-player .sidebar { + height: calc(100vh - 84px); +} + +.content { + padding: 28px clamp(16px, 4vw, 48px) 48px; + min-width: 0; +} + +.with-player .content { + padding-bottom: 120px; +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + padding: 0 10px 16px; + font-weight: 700; + font-size: 1.15rem; + letter-spacing: -0.01em; +} + +.brand-mark { + display: grid; + place-items: center; + width: 28px; + height: 28px; + border-radius: 8px; + background: var(--accent); + color: var(--accent-text); +} + +.rule-select { + width: calc(100% - 20px); + margin: 0 10px 8px; + padding: 6px 8px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface-2); +} + +.rule-info { + display: flex; + align-items: center; + justify-content: space-between; + margin: 0 0 8px; + padding: 0 4px 0 10px; + color: var(--muted); + font-size: 0.85rem; +} + +.mix-list { + list-style: none; + margin: 0; + padding: 0; +} + +.mix-list a { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 10px; + border-radius: 8px; + text-decoration: none; + color: var(--text); +} + +.mix-list a:hover { + background: var(--surface-2); +} + +.mix-list a.selected { + background: hsl(var(--hue) var(--art-s) var(--art-l) / 18%); +} + +.mix-dot { + flex: none; + width: 12px; + height: 12px; + border-radius: 4px; + background: linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 12%))); +} + +.mix-dot.heart { + display: grid; + place-items: center; + background: none; + color: var(--heart); +} + +.mix-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 0.93rem; +} + +.count { + flex: none; + min-width: 22px; + padding: 1px 7px; + border-radius: 999px; + background: var(--accent); + color: var(--accent-text); + font-size: 0.75rem; + font-weight: 600; + text-align: center; +} + +.liked-link { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid var(--border); +} + +/* ---------- mix header ---------- */ + +.mix-header { + display: flex; + gap: 28px; + align-items: flex-end; + margin-bottom: 32px; +} + +.mix-art { + flex: none; + display: grid; + place-items: end start; + width: 200px; + height: 200px; + padding: 18px; + border-radius: 16px; + background: + radial-gradient(circle at 80% 15%, hsl(calc(var(--hue) + 60) 90% 75% / 70%), transparent 55%), + linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 18%))); + color: #fff; + box-shadow: var(--shadow); + font-weight: 800; + font-size: 1.5rem; + line-height: 1.1; + letter-spacing: -0.02em; + text-shadow: 0 1px 8px rgb(0 0 0 / 25%); + overflow-wrap: anywhere; +} + +.liked-view .mix-art { + place-items: center; +} + +.mix-info { + min-width: 0; +} + +.eyebrow { + margin: 0 0 4px; + color: var(--muted); + font-size: 0.78rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +h1 { + margin: 0 0 12px; + font-size: clamp(1.6rem, 3.4vw, 2.6rem); + line-height: 1.1; + letter-spacing: -0.025em; +} + +.tags { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0 0 12px; + padding: 0; + list-style: none; +} + +.tags li { + padding: 2px 10px; + border-radius: 999px; + background: hsl(var(--hue) var(--art-s) var(--art-l) / 16%); + font-size: 0.82rem; +} + +.mix-counts { + margin: 0 0 16px; + color: var(--muted); + font-size: 0.9rem; +} + +.mix-buttons { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.mix-buttons button { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 9px 16px; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--surface); + font-weight: 600; + cursor: pointer; +} + +.mix-buttons button.primary { + border-color: transparent; + background: var(--accent); + color: var(--accent-text); +} + +.mix-buttons button:disabled { + opacity: 0.5; + cursor: default; +} + +/* ---------- track lists ---------- */ + +section + section { + margin-top: 32px; +} + +h2 { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 8px; + font-size: 1.05rem; +} + +.empty { + color: var(--muted); +} + +.tracks { + margin: 0; + padding: 0; + list-style: none; +} + +.track { + display: grid; + grid-template-columns: 36px 44px minmax(0, 1fr) auto auto auto; + align-items: center; + gap: 12px; + padding: 6px 8px; + border-radius: 10px; +} + +.track:hover, +.track.active { + background: var(--surface); +} + +.track.active { + box-shadow: inset 3px 0 0 var(--accent); +} + +.track-play { + display: grid; + place-items: center; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + cursor: pointer; +} + +.track-icon { + display: none; +} + +.track:hover .track-number, +.track.active .track-number { + display: none; +} + +.track:hover .track-icon, +.track.active .track-icon, +.track-play:focus-visible .track-icon { + display: grid; + place-items: center; + color: var(--accent); +} + +.track-play:focus-visible .track-number { + display: none; +} + +.track-number { + color: var(--muted); + font-variant-numeric: tabular-nums; + font-size: 0.85rem; +} + +.cover { + position: relative; + display: grid; + place-items: center; + overflow: hidden; + border-radius: 6px; + background: var(--surface-2); + color: var(--muted); + font-weight: 700; +} + +.cover img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; +} + +.track-text { + min-width: 0; +} + +.track-title, +.track-sub { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.track-title { + font-weight: 600; +} + +.track.active .track-title { + color: var(--accent); +} + +.track-sub { + color: var(--muted); + font-size: 0.88rem; +} + +.match { + color: var(--muted); + font-size: 0.82rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.played { + padding: 1px 8px; + border-radius: 999px; + background: var(--surface-2); + color: var(--muted); + font-size: 0.75rem; + white-space: nowrap; +} + +.track-duration { + color: var(--muted); + font-size: 0.85rem; + font-variant-numeric: tabular-nums; +} + +.track-actions { + display: flex; + gap: 2px; +} + +.icon-button { + display: inline-grid; + place-items: center; + width: 34px; + height: 34px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + color: var(--muted); + cursor: pointer; +} + +.icon-button.small { + width: 28px; + height: 28px; +} + +.icon-button:hover { + background: var(--surface-2); + color: var(--text); +} + +.icon-button.liked { + color: var(--heart); +} + +/* ---------- player ---------- */ + +.player { + position: fixed; + inset: auto 0 0 0; + z-index: 10; + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr) minmax(0, 1fr); + align-items: center; + gap: 20px; + height: 84px; + padding: 0 20px; + border-top: 1px solid var(--border); + background: color-mix(in srgb, var(--surface) 92%, transparent); + backdrop-filter: blur(12px); +} + +.player-track { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; +} + +.badge { + flex: none; + padding: 1px 8px; + border-radius: 999px; + border: 1px solid currentColor; + font-size: 0.72rem; + font-weight: 600; +} + +.badge.youtube { + color: var(--youtube); +} + +.badge.library { + color: var(--library); +} + +.player-main { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; +} + +.player-buttons { + display: flex; + align-items: center; + gap: 10px; +} + +.play-button { + display: grid; + place-items: center; + width: 40px; + height: 40px; + border: 0; + border-radius: 50%; + background: var(--text); + color: var(--bg); + cursor: pointer; +} + +.player-progress { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + color: var(--muted); + font-size: 0.75rem; + font-variant-numeric: tabular-nums; +} + +.player-progress span { + width: 38px; + text-align: center; +} + +.player-progress input { + flex: 1; + height: 4px; + appearance: none; + border-radius: 2px; + background: linear-gradient(to right, var(--accent) var(--progress), var(--border) var(--progress)); + cursor: pointer; +} + +.player-progress input::-webkit-slider-thumb { + appearance: none; + width: 12px; + height: 12px; + border-radius: 50%; + background: var(--text); +} + +.player-progress input::-moz-range-thumb { + width: 12px; + height: 12px; + border: 0; + border-radius: 50%; + background: var(--text); +} + +.player-status { + position: absolute; + top: -26px; + padding: 2px 10px; + border-radius: 999px; + background: var(--surface-2); + font-size: 0.78rem; + white-space: nowrap; +} + +.player-status.error { + color: var(--youtube); +} + +.player-queue { + justify-self: end; + color: var(--muted); + font-size: 0.85rem; + font-variant-numeric: tabular-nums; +} + +/* ---------- feedback ---------- */ + +.spinner { + display: inline-block; + width: 16px; + height: 16px; + border: 2px solid var(--border); + border-top-color: var(--accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; + vertical-align: middle; +} + +.spinner.light { + border-color: color-mix(in srgb, var(--bg) 35%, transparent); + border-top-color: var(--bg); +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +.bars { + display: flex; + align-items: flex-end; + gap: 2px; + height: 14px; +} + +.bars i { + width: 3px; + background: var(--accent); + animation: bar 0.9s ease-in-out infinite; +} + +.bars i:nth-child(2) { + animation-delay: -0.3s; +} + +.bars i:nth-child(3) { + animation-delay: -0.6s; +} + +@keyframes bar { + 0%, + 100% { + height: 30%; + } + 50% { + height: 100%; + } +} + +@media (prefers-reduced-motion: reduce) { + .bars i, + .spinner { + animation: none; + } +} + +.notice { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 24px; + padding: 16px 20px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.notice.error { + border-color: var(--youtube); + color: var(--youtube); +} + +.notice pre { + overflow-x: auto; + margin: 0; + padding: 12px; + border-radius: 8px; + background: var(--surface-2); + font-size: 0.85rem; +} + +.toast { + position: fixed; + left: 50%; + bottom: 104px; + z-index: 20; + display: flex; + align-items: center; + gap: 14px; + max-width: calc(100vw - 32px); + padding: 10px 16px; + border-radius: 10px; + background: var(--text); + color: var(--bg); + box-shadow: var(--shadow); + transform: translateX(-50%); +} + +.app:not(.with-player) .toast { + bottom: 24px; +} + +.toast button { + border: 0; + background: none; + color: var(--accent); + font-weight: 700; + cursor: pointer; +} + +/* ---------- tracked playlists ---------- */ + +.manage { + max-width: 980px; +} + +.manage-header { + margin-bottom: 24px; +} + +.manage-link { + margin-top: 2px; +} + +.manage-link .mix-dot { + color: var(--muted); +} + +.panel { + padding: 18px 20px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.panel + .panel { + margin-top: 20px; +} + +.panel-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 12px; +} + +.panel-header h2 { + margin: 0 0 2px; +} + +.hint { + margin: 0; + color: var(--muted); + font-size: 0.85rem; +} + +.hint code, +.template { + padding: 1px 5px; + border-radius: 4px; + background: var(--surface-2); + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.85em; +} + +.template { + font-size: 0.95em; +} + +.items { + margin: 0; + padding: 0; + list-style: none; +} + +.item { + border-top: 1px solid var(--border); +} + +.item-row { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto auto; + align-items: center; + gap: 14px; + padding: 12px 0; +} + +.item-icon { + display: grid; + place-items: center; + width: 40px; + height: 40px; + border-radius: 10px; + background: var(--surface-2); + color: var(--muted); +} + +.item-title { + overflow: hidden; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.item-sub, +.item-aside { + color: var(--muted); + font-size: 0.88rem; +} + +.item-aside { + white-space: nowrap; +} + +.item-actions { + display: flex; + gap: 6px; +} + +.warning-text { + color: var(--youtube); +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 34px; + padding: 6px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); + font-size: 0.88rem; + font-weight: 600; + white-space: nowrap; + cursor: pointer; +} + +.btn:hover:not(:disabled) { + background: var(--surface-2); +} + +.btn:disabled { + opacity: 0.55; + cursor: default; +} + +.btn.icon-only { + width: 34px; + padding: 0; + color: var(--muted); +} + +.btn.primary { + border-color: transparent; + background: var(--accent); + color: var(--accent-text); +} + +.btn.primary:hover:not(:disabled) { + background: color-mix(in srgb, var(--accent) 88%, var(--text)); +} + +.btn.danger { + border-color: transparent; + background: var(--youtube); + color: #fff; +} + +.btn .spinner { + width: 14px; + height: 14px; +} + +.form, +.confirm { + display: flex; + flex-direction: column; + gap: 14px; + margin: 4px 0 16px; + padding: 16px; + border-radius: 10px; + background: var(--surface-2); +} + +.item.editing .form { + margin: 12px 0; +} + +.confirm { + margin-top: 0; +} + +.confirm p { + margin: 0; +} + +.form-grid { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1.2fr) 100px; + gap: 12px; +} + +.field { + display: flex; + flex-direction: column; + gap: 5px; + min-width: 0; +} + +.field.wide { + grid-column: 1 / -1; +} + +.field > span, +.field > label { + font-size: 0.82rem; + font-weight: 600; +} + +.field input, +.field select { + width: 100%; + min-height: 38px; + padding: 7px 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); +} + +.field input.mono { + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; +} + +.checkbox { + display: flex; + align-items: center; + gap: 8px; + font-size: 0.92rem; +} + +.checkbox input { + width: 16px; + height: 16px; + accent-color: var(--youtube); +} + +.form-error { + margin: 0; + color: var(--youtube); + font-size: 0.9rem; +} + +.form-actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} + +.segmented { + display: inline-flex; + align-self: flex-start; + padding: 3px; + border-radius: 9px; + background: var(--surface); + border: 1px solid var(--border); +} + +.segmented button { + padding: 5px 12px; + border: 0; + border-radius: 6px; + background: none; + color: var(--muted); + font-size: 0.88rem; + font-weight: 600; + cursor: pointer; +} + +.segmented button[aria-checked="true"] { + background: var(--accent); + color: var(--accent-text); +} + +/* ---------- login & account ---------- */ + +.auth-page { + display: grid; + place-items: center; + min-height: 100vh; + padding: 24px 16px; +} + +.auth-card { + display: flex; + flex-direction: column; + gap: 16px; + width: 100%; + max-width: 380px; + padding: 28px 24px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); + box-shadow: var(--shadow); +} + +.auth-card .brand { + padding: 0; +} + +.auth-card h1 { + margin: 0 0 4px; + font-size: 1.4rem; +} + +.auth-card .btn { + min-height: 40px; +} + +.auth-page .notice { + align-items: flex-start; + max-width: 480px; +} + +.account-link { + margin-top: 2px; +} + +.account-link .mix-dot { + color: var(--muted); +} + +.token-status { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 4px; + font-size: 0.92rem; +} + +.status-dot { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--muted); +} + +.status-dot.ok { + background: var(--library); +} + +.hint a { + color: var(--accent); +} + +/* ---------- small screens ---------- */ + +@media (max-width: 800px) { + .app { + grid-template-columns: minmax(0, 1fr); + } + + .sidebar, + .with-player .sidebar { + position: static; + height: auto; + padding: 14px 16px 10px; + border-right: 0; + border-bottom: 1px solid var(--border); + } + + .brand { + padding: 0 0 10px; + } + + .rule-info { + padding: 0; + } + + .mix-list { + display: flex; + gap: 6px; + overflow-x: auto; + margin: 0 -16px; + padding: 0 16px 4px; + scrollbar-width: none; + } + + .mix-list a { + border: 1px solid var(--border); + border-radius: 999px; + padding: 6px 12px; + } + + .mix-name { + overflow: visible; + } + + .liked-link, + .manage-link, + .account-link { + margin: 0; + padding: 0; + border: 0; + } + + .content { + padding: 20px 16px 40px; + } + + .mix-header { + flex-direction: column; + align-items: stretch; + gap: 18px; + } + + .mix-art { + width: 100%; + height: 140px; + } + + .track { + grid-template-columns: 32px 40px minmax(0, 1fr) auto; + gap: 10px; + padding: 6px 0; + } + + .track-meta, + .track-duration, + .track-album { + display: none; + } + + .panel { + padding: 14px; + } + + .panel-header { + flex-direction: column; + } + + .item-row { + grid-template-columns: 36px minmax(0, 1fr); + gap: 4px 12px; + } + + .item-icon { + width: 36px; + height: 36px; + } + + .item-aside, + .item-actions { + grid-column: 2; + } + + .item-actions { + flex-wrap: wrap; + margin-top: 6px; + } + + .form-grid { + grid-template-columns: minmax(0, 1fr) 90px; + } + + .form-grid .field:not(.wide):not(.narrow) { + grid-column: 1 / -1; + } + + .player { + grid-template-columns: minmax(0, 1fr) auto; + height: auto; + padding: 10px 16px; + gap: 12px; + } + + .player-main { + flex-direction: row-reverse; + } + + .player-progress, + .player-queue, + .player .badge { + display: none; + } + + .player-status { + right: 0; + top: -38px; + } + + .with-player .content { + padding-bottom: 110px; + } +} diff --git a/discover/src/usePlayer.ts b/discover/src/usePlayer.ts new file mode 100644 index 0000000..e04da4e --- /dev/null +++ b/discover/src/usePlayer.ts @@ -0,0 +1,136 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { QueueItem } from "./queue"; + +export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error"; + +export type Player = ReturnType; + +export function usePlayer(onError: (item: QueueItem) => void) { + const audio = useRef(null); + if (audio.current === null && typeof Audio !== "undefined") { + audio.current = new Audio(); + audio.current.preload = "auto"; + } + + const [queue, setQueue] = useState([]); + const [index, setIndex] = useState(-1); + const [status, setStatus] = useState("idle"); + const [time, setTime] = useState(0); + const [duration, setDuration] = useState(0); + const current = index >= 0 ? queue[index] : undefined; + + // keep the latest values for the audio element's event handlers + const state = useRef({ queue, index, onError }); + state.current = { queue, index, onError }; + + const playAt = useCallback((items: QueueItem[], at: number) => { + setQueue(items); + setIndex(at); + }, []); + + const next = useCallback(() => { + const { queue, index } = state.current; + if (index + 1 < queue.length) setIndex(index + 1); + else { + audio.current?.pause(); + setStatus("paused"); + } + }, []); + + const previous = useCallback(() => { + const el = audio.current; + if (el && el.currentTime > 3) el.currentTime = 0; + else setIndex((i) => Math.max(0, i - 1)); + }, []); + + const toggle = useCallback(() => { + const el = audio.current; + if (!el || !state.current.queue.length) return; + if (el.paused) void el.play().catch(() => undefined); + else el.pause(); + }, []); + + const seek = useCallback((seconds: number) => { + if (!audio.current) return; + audio.current.currentTime = seconds; + // update now, or the controlled slider snaps back and its change event seeks back too + setTime(seconds); + }, []); + + // load the current item + useEffect(() => { + const el = audio.current; + if (!el || !current) return; + setTime(0); + setDuration(0); + setStatus("loading"); + el.src = current.src; + void el.play().catch(() => undefined); + }, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + const el = audio.current; + if (!el) return; + let errorTimer: number | undefined; + const handlers: Record void> = { + playing: () => setStatus("playing"), + pause: () => setStatus((s) => (s === "error" ? s : "paused")), + waiting: () => setStatus("loading"), + timeupdate: () => setTime(el.currentTime), + durationchange: () => setDuration(Number.isFinite(el.duration) ? el.duration : 0), + ended: () => next(), + error: () => { + if (!el.src) return; + setStatus("error"); + const { queue, index, onError } = state.current; + if (queue[index]) onError(queue[index]); + errorTimer = window.setTimeout(next, 1500); + }, + }; + for (const [event, handler] of Object.entries(handlers)) el.addEventListener(event, handler); + return () => { + window.clearTimeout(errorTimer); + for (const [event, handler] of Object.entries(handlers)) el.removeEventListener(event, handler); + }; + }, [next]); + + // stop playing when the app goes away (e.g. on logging out) + useEffect( + () => () => { + const el = audio.current; + if (!el) return; + el.pause(); + el.removeAttribute("src"); + el.load(); + }, + [], + ); + + // OS media controls and keyboard + useEffect(() => { + if (!("mediaSession" in navigator) || !current) return; + navigator.mediaSession.metadata = new MediaMetadata({ + title: current.title, + artist: current.artist, + album: current.album ?? undefined, + artwork: current.cover ? [{ src: current.cover }] : [], + }); + navigator.mediaSession.setActionHandler("play", toggle); + navigator.mediaSession.setActionHandler("pause", toggle); + navigator.mediaSession.setActionHandler("nexttrack", next); + navigator.mediaSession.setActionHandler("previoustrack", previous); + }, [current, toggle, next, previous]); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + const target = e.target as HTMLElement; + if (e.code !== "Space" || ["INPUT", "TEXTAREA", "BUTTON"].includes(target.tagName)) return; + e.preventDefault(); + toggle(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [toggle]); + + return { queue, index, current, status, time, duration, playAt, next, previous, toggle, seek }; +} diff --git a/discover/tsconfig.json b/discover/tsconfig.json new file mode 100644 index 0000000..4515ae8 --- /dev/null +++ b/discover/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "skipLibCheck": true, + "isolatedModules": true, + "noEmit": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/discover/vite.config.ts b/discover/vite.config.ts new file mode 100644 index 0000000..019b8d4 --- /dev/null +++ b/discover/vite.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; + +// During development, API requests go to playlistd (PLAYLISTD_URL, default localhost:8000) +export default defineConfig({ + plugins: [react()], + server: { + proxy: { + "/api": process.env.PLAYLISTD_URL ?? "http://localhost:8000", + }, + }, +}); diff --git a/etc/playlistd/playlistd.toml b/etc/playlistd/playlistd.toml index 3ce6e9a..cf4a0b3 100644 --- a/etc/playlistd/playlistd.toml +++ b/etc/playlistd/playlistd.toml @@ -6,6 +6,11 @@ username = "admin" # Your subsonic password password = "" +[log] +# error, warn, info (default), debug or trace. RUST_LOG overrides this when set, +# e.g. RUST_LOG=playlistd=debug,rocket=info +# level = "info" + [daemon] # How often to refresh playlists (in seconds) interval = 240 @@ -13,3 +18,18 @@ interval = 240 [database] # URL of database to use url = "postgres:///navidrome-playlists" + +[listenbrainz] +# Your Listenbrainz user token (listenbrainz.org/settings). Optional: lets the discover UI +# find new songs for each mix's genres with LB Radio, on top of your recommendations. +# A token saved to your account in the web UI takes priority over this one +# token = "" + +[discover] +# Directory with the built discover UI (discover/dist) to serve at / +ui = "/usr/share/playlistd/discover" +# yt-dlp binary used to play suggested songs that aren't in your library +# ytdlp = "yt-dlp" +# Format to ask Subsonic to stream in ("raw" = no transcoding), e.g. "mp3" if your +# library has files browsers can't play +# format = "raw" diff --git a/migrations/20261113150000_cluster_mixes.sql b/migrations/20261113150000_cluster_mixes.sql new file mode 100644 index 0000000..7701873 --- /dev/null +++ b/migrations/20261113150000_cluster_mixes.sql @@ -0,0 +1,45 @@ +-- A rule that periodically clusters a user's recent listens by genre and +-- maintains one Subsonic "mix" playlist per cluster. +CREATE TABLE "cluster_mix_rule" +( + id UUID NOT NULL PRIMARY KEY, + tracking_user VARCHAR(250) NOT NULL, -- Listenbrainz user to cluster + months INT NOT NULL DEFAULT 3, -- How many months of listens to cluster + cluster_count INT, -- Number of mixes. NULL = choose automatically + playlist_size INT NOT NULL DEFAULT 50, -- Tracks per mix + familiar_ratio DOUBLE PRECISION NOT NULL DEFAULT 0.3, -- Share of each mix made of recently played songs + name_template VARCHAR(250) NOT NULL DEFAULT 'Mix: {label}', -- {label} is replaced by the mix's genres + refresh_hours INT NOT NULL DEFAULT 24, -- How often to rebuild the mixes + last_run TIMESTAMPTZ, -- When the mixes were last rebuilt + discovery_count INT NOT NULL DEFAULT 15 -- New songs to suggest per mix +); + +-- The Subsonic playlists currently owned by a cluster mix rule. +CREATE TABLE "cluster_mix_playlist" +( + id UUID NOT NULL PRIMARY KEY, + rule_id UUID NOT NULL REFERENCES "cluster_mix_rule" (id) ON DELETE CASCADE, + playlist_id VARCHAR(250) NOT NULL, -- ID of the playlist in subsonic + tags TEXT[] NOT NULL, -- Genres describing the cluster, used to keep playlists stable across rebuilds + name VARCHAR(250), -- Name of the playlist in subsonic + position INT NOT NULL DEFAULT 0, -- Order of the mix, most listened first + known_song_ids TEXT[] NOT NULL DEFAULT '{}' -- Songs in the playlist the user played in the clustered period +); + +-- Songs not in the library, recommended by Listenbrainz and matched to a mix by genre +CREATE TABLE "mix_suggestion" +( + id UUID NOT NULL PRIMARY KEY, + rule_id UUID NOT NULL REFERENCES "cluster_mix_rule" (id) ON DELETE CASCADE, + mix_id UUID REFERENCES "cluster_mix_playlist" (id) ON DELETE SET NULL, + recording_mbid VARCHAR(36) NOT NULL, + title VARCHAR(500) NOT NULL, + artist VARCHAR(500) NOT NULL, + release VARCHAR(500), + cover_url TEXT, + score DOUBLE PRECISION NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'new', -- new, liked or dismissed + youtube_id VARCHAR(32), -- Cached YouTube match + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (rule_id, recording_mbid) +); diff --git a/migrations/20261116120000_users.sql b/migrations/20261116120000_users.sql new file mode 100644 index 0000000..a96d8be --- /dev/null +++ b/migrations/20261116120000_users.sql @@ -0,0 +1,21 @@ +-- The account that logs in to the web UI. The first visit to the UI creates it. +CREATE TABLE "app_user" +( + id UUID NOT NULL PRIMARY KEY, + username VARCHAR(64) NOT NULL UNIQUE, + password_hash TEXT NOT NULL, -- Argon2id, in PHC string format + listenbrainz_token TEXT, -- Used for Listenbrainz endpoints that need one (e.g. LB Radio) + listenbrainz_user VARCHAR(250), -- The Listenbrainz user the token belongs to + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- Logged in browsers. Only a hash of the session token is stored. +CREATE TABLE "user_session" +( + token_hash BYTEA NOT NULL PRIMARY KEY, -- SHA-256 of the token in the session cookie + user_id UUID NOT NULL REFERENCES "app_user" (id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + expires_at TIMESTAMPTZ NOT NULL +); + +CREATE INDEX "user_session_expires_at" ON "user_session" (expires_at); diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..0599a30 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,396 @@ +//! Login for the web UI and its API. +//! +//! The first visit to the UI creates the account (there's no default one); after that, every API +//! request needs a session cookie from logging in. Passwords are hashed with Argon2id, and only a +//! SHA-256 hash of each session token is stored, so the database alone can't be used to log in. + +use crate::listenbrainz; +use argon2::password_hash::{ + rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString, +}; +use argon2::Argon2; +use rand::RngCore; +use rocket::http::{Cookie, CookieJar, SameSite, Status}; +use rocket::request::{FromRequest, Outcome}; +use rocket::response::status::Custom; +use rocket::serde::json::Json; +use rocket::{catch, get, post, put, routes, Request, Route, State}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use sqlx::postgres::PgPool; +use std::sync::OnceLock; +use uuid::Uuid; + +pub const COOKIE: &str = "playlistd_session"; +const SESSION_DAYS: i64 = 30; +const MIN_PASSWORD: usize = 8; +const MAX_USERNAME: usize = 64; + +pub fn routes() -> Vec { + routes![ + status, + setup, + login, + logout, + account, + set_listenbrainz_token + ] +} + +#[derive(Serialize)] +pub struct ApiError { + error: String, +} + +type ApiResult = Result, Custom>>; + +fn error(status: Status, message: impl Into) -> Custom> { + Custom( + status, + Json(ApiError { + error: message.into(), + }), + ) +} + +fn db_error(e: sqlx::Error) -> Custom> { + log::error!("Database error: {}", e); + error(Status::InternalServerError, "Database error") +} + +/// API requests without a valid session get this instead of Rocket's HTML page +#[catch(401)] +pub fn unauthorized() -> Json { + Json(ApiError { + error: "Log in to continue".to_string(), + }) +} + +/// The logged in user. Add it as a request guard to a route to require logging in: requests +/// without a valid session fail with 401. +pub struct User { + pub id: Uuid, +} + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for User { + type Error = (); + + async fn from_request(request: &'r Request<'_>) -> Outcome { + let Some(token) = request.cookies().get(COOKIE).map(|c| c.value().to_string()) else { + return Outcome::Error((Status::Unauthorized, ())); + }; + let pool = match request.guard::<&State>().await { + Outcome::Success(pool) => pool, + _ => return Outcome::Error((Status::InternalServerError, ())), + }; + match sqlx::query_scalar!( + r#"SELECT user_id FROM "user_session" WHERE token_hash = $1 AND expires_at > NOW()"#, + &hash_token(&token)[..] + ) + .fetch_optional(pool.inner()) + .await + { + Ok(Some(id)) => Outcome::Success(User { id }), + Ok(None) => Outcome::Error((Status::Unauthorized, ())), + Err(e) => { + log::error!("Database error checking session: {}", e); + Outcome::Error((Status::InternalServerError, ())) + } + } + } +} + +fn hash_token(token: &str) -> Vec { + Sha256::digest(token.as_bytes()).to_vec() +} + +/// Argon2 is deliberately slow, so it runs off the async workers +async fn hash_password(password: String) -> Result>> { + tokio::task::spawn_blocking(move || { + let salt = SaltString::generate(&mut OsRng); + Argon2::default() + .hash_password(password.as_bytes(), &salt) + .map(|h| h.to_string()) + }) + .await + .ok() + .and_then(Result::ok) + .ok_or_else(|| error(Status::InternalServerError, "Couldn't hash the password")) +} + +async fn verify_password(password: String, hash: String) -> bool { + tokio::task::spawn_blocking(move || { + PasswordHash::new(&hash) + .map(|parsed| { + Argon2::default() + .verify_password(password.as_bytes(), &parsed) + .is_ok() + }) + .unwrap_or(false) + }) + .await + .unwrap_or(false) +} + +/// A hash to check passwords against when the username doesn't exist, so that a wrong username +/// takes as long as a wrong password +fn dummy_hash() -> &'static str { + static HASH: OnceLock = OnceLock::new(); + HASH.get_or_init(|| { + Argon2::default() + .hash_password(b"not a password", &SaltString::generate(&mut OsRng)) + .map(|h| h.to_string()) + .unwrap_or_default() + }) +} + +/// Start a session for a user and give the browser its cookie +async fn start_session( + pool: &PgPool, + cookies: &CookieJar<'_>, + user_id: Uuid, +) -> Result<(), Custom>> { + let mut bytes = [0u8; 32]; + rand::rngs::OsRng.fill_bytes(&mut bytes); + let token: String = bytes.iter().map(|b| format!("{:02x}", b)).collect(); + + sqlx::query!(r#"DELETE FROM "user_session" WHERE expires_at <= NOW()"#) + .execute(pool) + .await + .map_err(db_error)?; + sqlx::query!( + r#" + INSERT INTO "user_session" (token_hash, user_id, expires_at) + VALUES ($1, $2, NOW() + make_interval(days => $3)) + "#, + &hash_token(&token)[..], + user_id, + SESSION_DAYS as i32 + ) + .execute(pool) + .await + .map_err(db_error)?; + + cookies.add( + Cookie::build((COOKIE, token)) + .path("/") + .http_only(true) + .same_site(SameSite::Strict) + .max_age(rocket::time::Duration::days(SESSION_DAYS)), + ); + Ok(()) +} + +#[derive(Serialize)] +struct Account { + username: String, + /// The Listenbrainz user the saved token belongs to. The token itself is never sent back. + listenbrainz_user: Option, + has_listenbrainz_token: bool, +} + +async fn load_account(pool: &PgPool, id: Uuid) -> Result>> { + sqlx::query_as!( + Account, + r#" + SELECT username, listenbrainz_user, listenbrainz_token IS NOT NULL AS "has_listenbrainz_token!" + FROM "app_user" WHERE id = $1 + "#, + id + ) + .fetch_one(pool) + .await + .map_err(db_error) +} + +#[derive(Serialize)] +struct AuthStatus { + /// No account exists yet, so the UI should ask for a username and password to create one + setup_required: bool, + /// The logged in account, if any + account: Option, +} + +#[get("/status")] +async fn status(pool: &State, user: Option) -> ApiResult { + let setup_required = + !sqlx::query_scalar!(r#"SELECT EXISTS (SELECT 1 FROM "app_user") AS "e!""#) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + let account = match user { + Some(user) => Some(load_account(pool.inner(), user.id).await?), + None => None, + }; + Ok(Json(AuthStatus { + setup_required, + account, + })) +} + +#[derive(Deserialize)] +struct Credentials { + username: String, + password: String, +} + +/// Create the account. Only works while there isn't one yet. +#[post("/setup", data = "")] +async fn setup( + pool: &State, + cookies: &CookieJar<'_>, + credentials: Json, +) -> ApiResult { + let username = credentials.username.trim().to_string(); + if username.is_empty() || username.chars().count() > MAX_USERNAME { + return Err(error( + Status::UnprocessableEntity, + format!("Choose a username of 1 to {} characters", MAX_USERNAME), + )); + } + if credentials.password.chars().count() < MIN_PASSWORD { + return Err(error( + Status::UnprocessableEntity, + format!("Use a password of at least {} characters", MIN_PASSWORD), + )); + } + let password_hash = hash_password(credentials.password.clone()).await?; + + // the lock makes concurrent setups wait, so only the first one creates an account + let mut tx = pool.begin().await.map_err(db_error)?; + sqlx::query!(r#"LOCK TABLE "app_user" IN SHARE ROW EXCLUSIVE MODE"#) + .execute(&mut *tx) + .await + .map_err(db_error)?; + let exists = sqlx::query_scalar!(r#"SELECT EXISTS (SELECT 1 FROM "app_user") AS "e!""#) + .fetch_one(&mut *tx) + .await + .map_err(db_error)?; + if exists { + return Err(error( + Status::Conflict, + "The account has already been set up", + )); + } + let id = Uuid::new_v4(); + sqlx::query!( + r#"INSERT INTO "app_user" (id, username, password_hash) VALUES ($1, $2, $3)"#, + id, + username, + password_hash + ) + .execute(&mut *tx) + .await + .map_err(db_error)?; + tx.commit().await.map_err(db_error)?; + log::info!("Created account {}", username); + + start_session(pool.inner(), cookies, id).await?; + load_account(pool.inner(), id).await.map(Json) +} + +#[post("/login", data = "")] +async fn login( + pool: &State, + cookies: &CookieJar<'_>, + credentials: Json, +) -> ApiResult { + let user = sqlx::query!( + r#"SELECT id, password_hash FROM "app_user" WHERE username = $1"#, + credentials.username.trim() + ) + .fetch_optional(pool.inner()) + .await + .map_err(db_error)?; + + let hash = user + .as_ref() + .map(|u| u.password_hash.clone()) + .unwrap_or_else(|| dummy_hash().to_string()); + let valid = verify_password(credentials.password.clone(), hash).await; + match user { + Some(user) if valid => { + start_session(pool.inner(), cookies, user.id).await?; + load_account(pool.inner(), user.id).await.map(Json) + } + _ => { + log::warn!("Failed login for {:?}", credentials.username.trim()); + Err(error(Status::Unauthorized, "Wrong username or password")) + } + } +} + +#[post("/logout")] +async fn logout( + pool: &State, + cookies: &CookieJar<'_>, +) -> Result>> { + if let Some(cookie) = cookies.get(COOKIE) { + sqlx::query!( + r#"DELETE FROM "user_session" WHERE token_hash = $1"#, + &hash_token(cookie.value())[..] + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + } + cookies.remove(Cookie::build(COOKIE).path("/")); + Ok(Status::NoContent) +} + +#[get("/account")] +async fn account(pool: &State, user: User) -> ApiResult { + load_account(pool.inner(), user.id).await.map(Json) +} + +#[derive(Deserialize)] +struct ListenbrainzToken { + /// Empty or missing removes the saved token + token: Option, +} + +/// Save a Listenbrainz user token to the account, after checking it with Listenbrainz +#[put("/account/listenbrainz", data = "")] +async fn set_listenbrainz_token( + pool: &State, + user: User, + body: Json, +) -> ApiResult { + let token = body + .token + .as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()); + + let listenbrainz_user = match token { + Some(token) => match listenbrainz::validate_token(token).await { + Ok(Some(name)) => Some(name), + Ok(None) => { + return Err(error( + Status::UnprocessableEntity, + "Listenbrainz says that token isn't valid", + )) + } + Err(e) => { + log::warn!("Could not check Listenbrainz token: {}", e); + return Err(error( + Status::BadGateway, + "Couldn't reach Listenbrainz to check the token", + )); + } + }, + None => None, + }; + + sqlx::query!( + r#"UPDATE "app_user" SET listenbrainz_token = $1, listenbrainz_user = $2 WHERE id = $3"#, + token, + listenbrainz_user, + user.id + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + load_account(pool.inner(), user.id).await.map(Json) +} diff --git a/src/cluster.rs b/src/cluster.rs new file mode 100644 index 0000000..5f57c9d --- /dev/null +++ b/src/cluster.rs @@ -0,0 +1,539 @@ +//! Clustering of listened tracks by genre. +//! +//! Every track gets a TF-IDF vector over its MusicBrainz tags (recording, release +//! group and artist tags, as provided by the caller). To take listening habits +//! into account, each vector is then blended with the vectors of the tracks it +//! is usually played next to (within the same listening session), which also +//! gives untagged tracks a position. The vectors are grouped with spherical +//! k-means, weighted by play count, and each cluster is described by the tags +//! that are both common in it and distinctive compared to the rest. + +use rand::rngs::StdRng; +use rand::{Rng, SeedableRng}; +use std::collections::HashMap; + +pub struct Play { + /// Unix timestamp of the listen + pub ts: i64, + /// Identifies the track; listens with the same key are the same track + pub key: String, +} + +pub struct ClusterOptions { + /// Ignore tracks with fewer plays than this + pub min_plays: usize, + /// Fixed number of clusters. `None` picks one from `k_range` by silhouette score + pub cluster_count: Option, + pub k_range: (usize, usize), + /// Seconds of silence that end a listening session + pub session_gap: i64, + /// How many following tracks in a session count as played "together" + pub window: usize, + /// How strongly a track is pulled towards the tracks played around it + pub context_weight: f64, + pub seed: u64, +} + +impl Default for ClusterOptions { + fn default() -> Self { + Self { + min_plays: 2, + cluster_count: None, + k_range: (4, 10), + session_gap: 30 * 60, + window: 5, + context_weight: 0.5, + seed: 0, + } + } +} + +#[derive(Debug)] +pub struct Cluster { + /// Track keys and their play counts, most played first + pub tracks: Vec<(String, usize)>, + /// Total plays of the cluster's tracks + pub plays: usize, + /// Tags that characterise the cluster, most characteristic first + pub profile: Vec<(String, f64)>, +} + +const PROFILE_SIZE: usize = 40; +/// Profile tags need at least this fraction of the weight of the cluster's most common tag +const PROFILE_FLOOR: f64 = 0.2; +const N_INIT: usize = 5; +const MAX_ITER: usize = 100; +const SILHOUETTE_SAMPLE: usize = 1500; + +pub fn cluster( + plays: &[Play], + tags: &HashMap>, + opts: &ClusterOptions, +) -> Vec { + // ---- tracks ---- + let mut counts: HashMap<&str, usize> = HashMap::new(); + for p in plays { + *counts.entry(p.key.as_str()).or_default() += 1; + } + let mut keys: Vec<&str> = counts + .iter() + .filter(|(_, &n)| n >= opts.min_plays.max(1)) + .map(|(&k, _)| k) + .collect(); + keys.sort_by(|a, b| counts[b].cmp(&counts[a]).then(a.cmp(b))); + let n = keys.len(); + if n < 2 { + return vec![]; + } + let index: HashMap<&str, usize> = keys.iter().enumerate().map(|(i, &k)| (k, i)).collect(); + + // ---- tag TF-IDF ---- + let mut df: HashMap<&str, usize> = HashMap::new(); + for k in &keys { + for (tag, &w) in tags.get(*k).into_iter().flatten() { + if w > 0.0 { + *df.entry(tag.as_str()).or_default() += 1; + } + } + } + // tags on a single track can't relate tracks to each other + let mut vocab: Vec<&str> = df + .iter() + .filter(|(_, &d)| d >= 2) + .map(|(&t, _)| t) + .collect(); + vocab.sort(); + let dims = vocab.len(); + if dims == 0 { + return vec![]; + } + let vocab_index: HashMap<&str, usize> = + vocab.iter().enumerate().map(|(i, &t)| (t, i)).collect(); + let idf: Vec = vocab + .iter() + .map(|t| ((1 + n) as f64 / (1 + df[t]) as f64).ln() + 1.0) + .collect(); + + let mut tag_vecs = vec![vec![0.0; dims]; n]; + for (i, k) in keys.iter().enumerate() { + for (tag, &w) in tags.get(*k).into_iter().flatten() { + if let Some(&j) = vocab_index.get(tag.as_str()) { + if w > 0.0 { + tag_vecs[i][j] = (1.0 + w).ln() * idf[j]; + } + } + } + normalize(&mut tag_vecs[i]); + } + + // ---- listening context ---- + let mut order: Vec<&Play> = plays.iter().collect(); + order.sort_by_key(|p| p.ts); + let mut co: Vec> = vec![HashMap::new(); n]; + let mut session: Vec = vec![]; + let mut prev_ts: Option = None; + for p in order { + if prev_ts.is_some_and(|t| p.ts - t > opts.session_gap) { + add_cooccurrences(&session, opts.window, &mut co); + session.clear(); + } + if let Some(&i) = index.get(p.key.as_str()) { + session.push(i); + } + prev_ts = Some(p.ts); + } + add_cooccurrences(&session, opts.window, &mut co); + + let mut x: Vec> = Vec::with_capacity(n); + for i in 0..n { + let mut v = tag_vecs[i].clone(); + let total: f64 = co[i].values().sum(); + if total > 0.0 { + for (&j, &c) in &co[i] { + let f = opts.context_weight * c / total; + for (a, b) in v.iter_mut().zip(&tag_vecs[j]) { + *a += f * b; + } + } + } + normalize(&mut v); + x.push(v); + } + + // tracks with no tags and no tagged neighbours can't be placed + let placed: Vec = (0..n).filter(|&i| x[i].iter().any(|&v| v != 0.0)).collect(); + if placed.len() < 2 { + return vec![]; + } + let points: Vec> = placed.iter().map(|&i| x[i].clone()).collect(); + let weights: Vec = placed + .iter() + .map(|&i| (1.0 + counts[keys[i]] as f64).ln()) + .collect(); + + // ---- k-means ---- + let mut rng = StdRng::seed_from_u64(opts.seed); + let k = match opts.cluster_count { + Some(k) => k.clamp(1, points.len()), + None => choose_k(&points, &weights, opts.k_range, &mut rng), + }; + let labels = best_kmeans(&points, &weights, k, &mut rng); + + // ---- describe clusters ---- + let mut overall = vec![0.0; dims]; + let total_weight: f64 = weights.iter().sum(); + for (p, &i) in placed.iter().enumerate() { + for (o, v) in overall.iter_mut().zip(&tag_vecs[i]) { + *o += weights[p] * v / total_weight; + } + } + + let mut clusters = vec![]; + for c in 0..k { + let members: Vec = (0..placed.len()).filter(|&p| labels[p] == c).collect(); + if members.is_empty() { + continue; + } + let member_weight: f64 = members.iter().map(|&p| weights[p]).sum(); + let mut mean = vec![0.0; dims]; + for &p in &members { + for (m, v) in mean.iter_mut().zip(&tag_vecs[placed[p]]) { + *m += weights[p] * v / member_weight; + } + } + // frequent in the cluster AND over-represented compared to everything else, + // ignoring tags only a handful of the cluster's tracks have + let floor = PROFILE_FLOOR * mean.iter().cloned().fold(0.0, f64::max); + let mut profile: Vec<(String, f64)> = (0..dims) + .filter(|&j| mean[j] > 0.0 && mean[j] >= floor) + .map(|j| { + let score = mean[j] * (mean[j] / (overall[j] + 1e-9) + 1.0).ln(); + (vocab[j].to_string(), score) + }) + .collect(); + profile.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + profile.truncate(PROFILE_SIZE); + + let mut tracks: Vec<(String, usize)> = members + .iter() + .map(|&p| (keys[placed[p]].to_string(), counts[keys[placed[p]]])) + .collect(); + tracks.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + + clusters.push(Cluster { + plays: tracks.iter().map(|t| t.1).sum(), + tracks, + profile, + }); + } + clusters.sort_by_key(|c| std::cmp::Reverse(c.plays)); + clusters +} + +fn add_cooccurrences(session: &[usize], window: usize, co: &mut [HashMap]) { + for a in 0..session.len() { + for b in (a + 1)..(a + 1 + window).min(session.len()) { + let (i, j) = (session[a], session[b]); + if i != j { + // closer plays count more + let w = 1.0 / (b - a) as f64; + *co[i].entry(j).or_default() += w; + *co[j].entry(i).or_default() += w; + } + } + } +} + +fn normalize(v: &mut [f64]) { + let norm = dot(v, v).sqrt(); + if norm > 0.0 { + v.iter_mut().for_each(|x| *x /= norm); + } +} + +fn dot(a: &[f64], b: &[f64]) -> f64 { + a.iter().zip(b).map(|(x, y)| x * y).sum() +} + +fn argmax_similarity(point: &[f64], centroids: &[Vec]) -> (usize, f64) { + centroids + .iter() + .enumerate() + .map(|(c, centroid)| (c, dot(point, centroid))) + .fold((0, f64::NEG_INFINITY), |best, cur| { + if cur.1 > best.1 { + cur + } else { + best + } + }) +} + +fn weighted_choice(weights: &[f64], rng: &mut StdRng) -> usize { + let total: f64 = weights.iter().sum(); + if total <= 0.0 { + return rng.gen_range(0..weights.len()); + } + let mut r = rng.gen::() * total; + for (i, &w) in weights.iter().enumerate() { + r -= w; + if r <= 0.0 { + return i; + } + } + weights.len() - 1 +} + +/// Spherical k-means (cosine similarity) with k-means++ seeding. +/// Returns the labels and the objective (weighted sum of similarity to the centroid). +fn kmeans(x: &[Vec], w: &[f64], k: usize, rng: &mut StdRng) -> (Vec, f64) { + let n = x.len(); + let mut centroids = vec![x[weighted_choice(w, rng)].clone()]; + while centroids.len() < k { + let d: Vec = (0..n) + .map(|i| { + let (_, sim) = argmax_similarity(&x[i], ¢roids); + w[i] * (1.0 - sim).max(0.0).powi(2) + }) + .collect(); + centroids.push(x[weighted_choice(&d, rng)].clone()); + } + + let mut labels = vec![usize::MAX; n]; + for _ in 0..MAX_ITER { + let mut changed = false; + for i in 0..n { + let (c, _) = argmax_similarity(&x[i], ¢roids); + if labels[i] != c { + labels[i] = c; + changed = true; + } + } + if !changed { + break; + } + + let dims = x[0].len(); + let mut sums = vec![vec![0.0; dims]; k]; + let mut sizes = vec![0usize; k]; + for i in 0..n { + sizes[labels[i]] += 1; + for (s, v) in sums[labels[i]].iter_mut().zip(&x[i]) { + *s += w[i] * v; + } + } + for c in 0..k { + if sizes[c] == 0 { + // re-seed an empty cluster with the worst-fitting point + let worst = (0..n) + .min_by(|&a, &b| { + dot(&x[a], ¢roids[labels[a]]) + .total_cmp(&dot(&x[b], ¢roids[labels[b]])) + }) + .unwrap(); + sums[c] = x[worst].clone(); + labels[worst] = c; + } + normalize(&mut sums[c]); + } + centroids = sums; + } + + let objective = (0..n) + .map(|i| w[i] * dot(&x[i], ¢roids[labels[i]])) + .sum(); + (labels, objective) +} + +fn best_kmeans(x: &[Vec], w: &[f64], k: usize, rng: &mut StdRng) -> Vec { + (0..N_INIT) + .map(|_| kmeans(x, w, k, rng)) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .unwrap() + .0 +} + +/// Mean silhouette score using cosine distance, over the given sample of points. +fn silhouette(sim: &[Vec], labels: &[usize], k: usize) -> f64 { + let n = labels.len(); + let mut total = 0.0; + for i in 0..n { + let mut dist_sum = vec![0.0; k]; + let mut count = vec![0usize; k]; + for j in 0..n { + if i != j { + dist_sum[labels[j]] += 1.0 - sim[i][j]; + count[labels[j]] += 1; + } + } + if count[labels[i]] == 0 { + continue; // singleton clusters score 0 + } + let a = dist_sum[labels[i]] / count[labels[i]] as f64; + let b = (0..k) + .filter(|&c| c != labels[i] && count[c] > 0) + .map(|c| dist_sum[c] / count[c] as f64) + .fold(f64::INFINITY, f64::min); + if b.is_finite() && a.max(b) > 0.0 { + total += (b - a) / a.max(b); + } + } + total / n as f64 +} + +fn choose_k(x: &[Vec], w: &[f64], range: (usize, usize), rng: &mut StdRng) -> usize { + let n = x.len(); + let (lo, hi) = (range.0.max(2), range.1.min(n - 1)); + if lo > hi { + return range.0.clamp(1, n); + } + + // silhouette is quadratic, so score on a sample + let mut sample: Vec = (0..n).collect(); + for i in (1..n).rev() { + sample.swap(i, rng.gen_range(0..=i)); + } + sample.truncate(SILHOUETTE_SAMPLE); + let sim: Vec> = sample + .iter() + .map(|&i| sample.iter().map(|&j| dot(&x[i], &x[j])).collect()) + .collect(); + + let mut best = (f64::NEG_INFINITY, lo); + for k in lo..=hi { + let labels = best_kmeans(x, w, k, rng); + let sample_labels: Vec = sample.iter().map(|&i| labels[i]).collect(); + let score = silhouette(&sim, &sample_labels, k); + if score > best.0 { + best = (score, k); + } + } + best.1 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tags(pairs: &[(&str, &[&str])]) -> HashMap> { + pairs + .iter() + .map(|(k, ts)| { + ( + k.to_string(), + ts.iter().map(|t| (t.to_string(), 1.0)).collect(), + ) + }) + .collect() + } + + fn plays(keys: &[&str], repeats: usize) -> Vec { + let mut out = vec![]; + let mut ts = 0; + for _ in 0..repeats { + for k in keys { + out.push(Play { + ts, + key: k.to_string(), + }); + ts += 200; + } + ts += 10_000; // new session + } + out + } + + #[test] + fn separates_genres() { + let t = tags(&[ + ("m1", &["metal", "death metal"]), + ("m2", &["metal", "death metal"]), + ("m3", &["metal", "black metal"]), + ("f1", &["folk", "indie folk"]), + ("f2", &["folk", "indie folk"]), + ("f3", &["folk", "folk rock"]), + ]); + let p = plays(&["m1", "m2", "m3", "f1", "f2", "f3"], 3); + let opts = ClusterOptions { + cluster_count: Some(2), + context_weight: 0.0, + ..Default::default() + }; + let clusters = cluster(&p, &t, &opts); + + assert_eq!(clusters.len(), 2); + for c in &clusters { + let first = c.tracks[0].0.chars().next().unwrap(); + assert!( + c.tracks.iter().all(|(k, _)| k.starts_with(first)), + "{:?}", + c + ); + let top = &c.profile[0].0; + assert!(if first == 'm' { + top.contains("metal") + } else { + top.contains("folk") + }); + } + } + + #[test] + fn untagged_tracks_follow_context() { + let t = tags(&[ + ("m1", &["metal"]), + ("m2", &["metal"]), + ("f1", &["folk"]), + ("f2", &["folk"]), + ]); + // "x" has no tags but is always played straight after the metal tracks + let mut p = plays(&["m1", "m2", "x"], 3); + let offset = p.last().unwrap().ts + 100_000; + p.extend(plays(&["f1", "f2"], 3).into_iter().map(|mut pl| { + pl.ts += offset; + pl + })); + let opts = ClusterOptions { + cluster_count: Some(2), + ..Default::default() + }; + let clusters = cluster(&p, &t, &opts); + + let metal = clusters + .iter() + .find(|c| c.tracks.iter().any(|(k, _)| k == "m1")) + .unwrap(); + assert!(metal.tracks.iter().any(|(k, _)| k == "x")); + } + + #[test] + fn picks_k_automatically() { + let genres = ["metal", "folk", "hyperpop", "jazz"]; + let mut pairs: Vec<(String, Vec<&str>)> = vec![]; + for g in genres { + for i in 0..6 { + pairs.push((format!("{g}{i}"), vec![g, "music"])); + } + } + let t: HashMap> = pairs + .iter() + .map(|(k, ts)| (k.clone(), ts.iter().map(|t| (t.to_string(), 1.0)).collect())) + .collect(); + let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect(); + let p = plays(&keys, 2); + let opts = ClusterOptions { + k_range: (2, 8), + context_weight: 0.0, + ..Default::default() + }; + + assert_eq!(cluster(&p, &t, &opts).len(), 4); + } + + #[test] + fn too_little_data() { + let t = tags(&[("a", &["rock"])]); + assert!(cluster(&plays(&["a"], 3), &t, &ClusterOptions::default()).is_empty()); + assert!(cluster(&[], &t, &ClusterOptions::default()).is_empty()); + } +} diff --git a/src/daemon/cluster_mixes.rs b/src/daemon/cluster_mixes.rs new file mode 100644 index 0000000..cd3cf45 --- /dev/null +++ b/src/daemon/cluster_mixes.rs @@ -0,0 +1,367 @@ +use crate::cluster::{self, ClusterOptions, Play}; +use crate::discover::{self, MixTarget}; +use crate::listenbrainz; +use crate::mix::{self, ListenedTrack, MixOptions, RecentlyPlayed}; +use crate::models::{ClusterMixPlaylist, ClusterMixRule}; +use crate::subsonic::Subsonic; +use crate::CONFIG; +use chrono::Utc; +use rand::rngs::StdRng; +use rand::SeedableRng; +use sqlx::postgres::PgPool; +use std::collections::{HashMap, HashSet}; +use std::time::Duration; +use tokio::time::{interval, MissedTickBehavior}; +use uuid::Uuid; + +/// Clusters smaller than this don't get a mix +const MIN_CLUSTER_TRACKS: usize = 5; +const SECONDS_PER_MONTH: i64 = 30 * 24 * 60 * 60; + +pub async fn cluster_mixes_daemon( + media_client: impl AsRef + Clone, +) -> Result<(), Box> { + log::info!("Cluster mix daemon starting"); + + let database = PgPool::connect( + CONFIG + .get() + .unwrap() + .get::("database.url")? + .as_str(), + ) + .await + .unwrap(); + + let mut ticker = interval(Duration::from_secs( + CONFIG.get().unwrap().get::("daemon.interval")?, + )); + ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); + + let mut failures = super::Failures::default(); + loop { + // the first tick completes straight away + ticker.tick().await; + + match ClusterMixRule::due(&database).await { + Ok(rules) => { + for rule in rules { + // failed builds are retried every tick, so don't repeat the same error + let key = rule.id.to_string(); + let about = format!("cluster mixes for {}", rule.tracking_user); + match build_mixes(media_client.as_ref(), rule, &database).await { + Ok(()) => failures.succeeded(&key, &about), + Err(e) => { + failures.failed(&key, format!("Could not build {}: {}", about, e)) + } + } + } + } + + Err(e) => { + log::error!("Could not fetch cluster mix rules: {}", e); + } + } + } +} + +pub async fn build_mixes( + media_client: &Subsonic, + rule: ClusterMixRule, + database: &PgPool, +) -> Result<(), Box> { + let since = Utc::now().timestamp() - rule.months.max(1) as i64 * SECONDS_PER_MONTH; + let listens = listenbrainz::listens_since(&rule.tracking_user, since).await?; + + // ---- listening history ---- + let mut plays = Vec::with_capacity(listens.len()); + let mut listened: HashMap = HashMap::new(); + let mut recently_played = RecentlyPlayed::default(); + for listen in &listens { + let mbid = listen.recording_mbid(); + let metadata = &listen.track_metadata; + let key = mbid + .clone() + .unwrap_or_else(|| mix::name_key(&metadata.artist_name, &metadata.track_name)); + let track = ListenedTrack { + mbid, + artist: metadata.artist_name.clone(), + title: metadata.track_name.clone(), + }; + recently_played.insert(&track); + listened.entry(key.clone()).or_insert(track); + plays.push(Play { + ts: listen.listened_at, + key, + }); + } + + let mbids: Vec = listened.values().filter_map(|t| t.mbid.clone()).collect(); + let tags = listenbrainz::recording_tags(&mbids).await?; + + // ---- cluster ---- + let clusters = cluster::cluster( + &plays, + &tags, + &ClusterOptions { + cluster_count: rule.cluster_count.map(|k| k.max(1) as usize), + seed: Utc::now().timestamp() as u64, + ..Default::default() + }, + ); + log::info!( + "{}: {} listens over {} months -> {} clusters", + rule.tracking_user, + listens.len(), + rule.months, + clusters.len() + ); + + // ---- build mixes ---- + let library_genres = mix::genre_index( + media_client + .get_genres() + .await? + .into_iter() + .filter(|g| g.song_count > 0) + .map(|g| g.value), + ); + let options = MixOptions { + size: rule.playlist_size.max(1) as usize, + familiar_ratio: rule.familiar_ratio, + max_genres: 6, + songs_per_genre: 1000, + }; + let mut rng = StdRng::from_entropy(); + + let mut mixes = vec![]; + for cluster in clusters + .iter() + .filter(|c| c.tracks.len() >= MIN_CLUSTER_TRACKS) + { + match mix::build_mix( + media_client, + cluster, + &library_genres, + &listened, + &recently_played, + &options, + &mut rng, + ) + .await? + { + Some(mix) => mixes.push((mix, cluster)), + None => log::info!( + "No library genres match cluster {:?}", + cluster + .profile + .iter() + .take(3) + .map(|t| &t.0) + .collect::>() + ), + } + } + + // two clusters can share their top genres + let mut seen_labels: HashMap = HashMap::new(); + for (mix, _) in &mut mixes { + let n = seen_labels.entry(mix.label.clone()).or_default(); + *n += 1; + if *n > 1 { + mix.label = format!("{} ({})", mix.label, n); + } + } + + // ---- sync playlists, reusing the previous run's playlists where the genres overlap ---- + let existing = sqlx::query_as!( + ClusterMixPlaylist, + r#"SELECT * FROM "cluster_mix_playlist" WHERE rule_id = $1"#, + rule.id + ) + .fetch_all(database) + .await?; + + let pairs = mix::match_mixes( + &existing.iter().map(|p| p.tags.clone()).collect::>(), + &mixes + .iter() + .map(|(m, _)| m.tags.clone()) + .collect::>(), + ); + let old_for_new: HashMap = pairs.iter().map(|&(o, n)| (n, o)).collect(); + + let mut targets = vec![]; + for (n, (mix, cluster)) in mixes.iter().enumerate() { + let name = rule.name_template.replace("{label}", &mix.label); + let position = n as i32; + + let reused = match old_for_new.get(&n).map(|&o| &existing[o]) { + // the playlist may have been deleted by hand since the last run + Some(old) if media_client.get_playlist(&old.playlist_id).await.is_ok() => { + media_client + .rename_playlist(&old.playlist_id, &name) + .await?; + sqlx::query!( + r#"UPDATE "cluster_mix_playlist" SET tags = $1, name = $2, position = $3, known_song_ids = $4 WHERE id = $5"#, + &mix.tags, + name, + position, + &mix.known_song_ids, + old.id + ) + .execute(database) + .await?; + Some((old.id, old.playlist_id.clone())) + } + Some(old) => { + sqlx::query!( + r#"DELETE FROM "cluster_mix_playlist" WHERE id = $1"#, + old.id + ) + .execute(database) + .await?; + None + } + None => None, + }; + + let (mix_id, playlist_id) = match reused { + Some(ids) => ids, + None => { + let playlist = media_client.create_playlist(&name).await?; + let mix_id = Uuid::new_v4(); + sqlx::query!( + r#" + INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags, name, position, known_song_ids) + VALUES ($1, $2, $3, $4, $5, $6, $7) + "#, + mix_id, + rule.id, + playlist.id, + &mix.tags, + name, + position, + &mix.known_song_ids, + ) + .execute(database) + .await?; + (mix_id, playlist.id) + } + }; + targets.push(MixTarget { + mix_id, + profile: cluster.profile.clone(), + }); + + media_client + .replace_playlist_songs(&playlist_id, mix.song_ids.clone()) + .await?; + log::info!("Updated mix {:?} ({} songs)", name, mix.song_ids.len()); + } + + // mixes for tastes that no longer show up in the listening history + let kept: Vec = pairs.iter().map(|&(o, _)| o).collect(); + for (o, old) in existing.iter().enumerate() { + if !kept.contains(&o) { + if let Err(e) = media_client.delete_playlist(&old.playlist_id).await { + log::warn!("Could not delete playlist {}: {}", old.playlist_id, e); + } + sqlx::query!( + r#"DELETE FROM "cluster_mix_playlist" WHERE id = $1"#, + old.id + ) + .execute(database) + .await?; + } + } + + // ---- songs that aren't in the library ---- + // a failure here shouldn't stop the mixes from being marked as built + if let Err(e) = + save_suggestions(media_client, &rule, &targets, &recently_played, database).await + { + log::warn!("Could not find new songs for {}: {}", rule.tracking_user, e); + } + + sqlx::query!( + r#"UPDATE "cluster_mix_rule" SET last_run = NOW() WHERE id = $1"#, + rule.id + ) + .execute(database) + .await?; + + Ok(()) +} + +async fn save_suggestions( + media_client: &Subsonic, + rule: &ClusterMixRule, + targets: &[MixTarget], + recently_played: &RecentlyPlayed, + database: &PgPool, +) -> Result<(), Box> { + // liked and dismissed suggestions stay as they are + let exclude: HashSet = sqlx::query_scalar!( + r#"SELECT recording_mbid FROM "mix_suggestion" WHERE rule_id = $1 AND status <> 'new'"#, + rule.id + ) + .fetch_all(database) + .await? + .into_iter() + .collect(); + + let suggestions = discover::suggest( + media_client, + &rule.tracking_user, + targets, + recently_played, + &exclude, + rule.discovery_count.max(0) as usize, + listenbrainz::token(database).await, + ) + .await?; + + for s in &suggestions { + sqlx::query!( + r#" + INSERT INTO "mix_suggestion" (id, rule_id, mix_id, recording_mbid, title, artist, release, cover_url, score) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (rule_id, recording_mbid) DO UPDATE + SET mix_id = EXCLUDED.mix_id, score = EXCLUDED.score, title = EXCLUDED.title, + artist = EXCLUDED.artist, release = EXCLUDED.release, cover_url = EXCLUDED.cover_url + "#, + Uuid::new_v4(), + rule.id, + s.mix_id, + s.mbid, + s.info.title, + s.info.artist, + s.info.release, + s.info.cover_url, + s.score, + ) + .execute(database) + .await?; + } + + // drop untouched suggestions from previous runs + let kept: Vec = suggestions.iter().map(|s| s.mbid.clone()).collect(); + sqlx::query!( + r#" + DELETE FROM "mix_suggestion" + WHERE rule_id = $1 AND status = 'new' AND NOT (recording_mbid = ANY($2)) + "#, + rule.id, + &kept, + ) + .execute(database) + .await?; + + log::info!( + "{}: {} new songs suggested", + rule.tracking_user, + suggestions.len() + ); + Ok(()) +} diff --git a/src/daemon/create_playlists.rs b/src/daemon/create_playlists.rs index 6727712..51a185c 100644 --- a/src/daemon/create_playlists.rs +++ b/src/daemon/create_playlists.rs @@ -10,7 +10,7 @@ use uuid::Uuid; pub async fn create_playlists_daemon( media_client: impl AsRef + Clone, ) -> Result<(), Box> { - println!("Create playlist daemon starting..."); + log::info!("Playlist rule daemon starting"); let database = PgPool::connect( CONFIG @@ -27,7 +27,11 @@ pub async fn create_playlists_daemon( )); ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut failures = super::Failures::default(); loop { + // the first tick completes straight away + ticker.tick().await; + let records_res = sqlx::query_as!( CreateTrackedPlaylist, r#"SELECT * FROM "create_tracked_playlist""# @@ -38,19 +42,19 @@ pub async fn create_playlists_daemon( match records_res { Ok(records) => { for record in records { - // todo handle me - create_playlist(media_client.clone(), record, database.clone()) - .await - .unwrap(); + let key = record.id.to_string(); + let about = format!("playlist rule {:?}", record.name_template); + match create_playlist(media_client.clone(), record, database.clone()).await { + Ok(()) => failures.succeeded(&key, &about), + Err(e) => failures.failed(&key, format!("Could not run {}: {}", about, e)), + } } } Err(e) => { - println!("Could not fetch create_tracked_playlist: {:?}", e); + log::error!("Could not fetch playlist rules: {}", e); } } - - ticker.tick().await; } } @@ -63,6 +67,7 @@ async fn create_playlist( let new_name = now.format(&playlist_rule.name_template).to_string(); if Some(&new_name) != playlist_rule.last_name.as_ref() { + log::info!("Creating playlist {:?}", new_name); // Create playlist let playlist = media_client.as_ref().create_playlist(&new_name).await?; let uuid = Uuid::new_v4(); diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs index e5f4dd7..9f5134d 100644 --- a/src/daemon/mod.rs +++ b/src/daemon/mod.rs @@ -1,5 +1,31 @@ +pub mod cluster_mixes; pub mod create_playlists; pub mod update_playlists; +pub use cluster_mixes::cluster_mixes_daemon; pub use create_playlists::create_playlists_daemon; pub use update_playlists::update_playlists_daemon; + +use std::collections::HashMap; + +/// Logs a recurring job's failures without repeating the same warning on every run: an error is +/// a warning when it first happens or changes, and debug output while it keeps happening. +#[derive(Default)] +pub struct Failures(HashMap); + +impl Failures { + pub fn failed(&mut self, key: &str, message: String) { + if self.0.get(key) == Some(&message) { + log::debug!("Still failing: {}", message); + } else { + log::warn!("{}", message); + self.0.insert(key.to_string(), message); + } + } + + pub fn succeeded(&mut self, key: &str, what: impl std::fmt::Display) { + if self.0.remove(key).is_some() { + log::info!("{} is working again", what); + } + } +} diff --git a/src/daemon/update_playlists.rs b/src/daemon/update_playlists.rs index c4f052c..41ec0a3 100644 --- a/src/daemon/update_playlists.rs +++ b/src/daemon/update_playlists.rs @@ -1,8 +1,9 @@ +use crate::listenbrainz::ListenbrainzError; use crate::listenbrainz::StatsRange; use crate::models::TrackedPlaylist; use crate::subsonic::Subsonic; use crate::{listenbrainz, CONFIG}; -use log::{error, warn}; +use log::{debug, error, info}; use sqlx::postgres::PgPool; use std::time::Duration; use thiserror::Error; @@ -19,7 +20,7 @@ pub enum UpdatePlaylistError { pub async fn update_playlists_daemon( media_client: impl AsRef + Clone, ) -> Result<(), Box> { - println!("Track playlist daemon starting..."); + info!("Tracked playlist daemon starting"); let database = PgPool::connect( CONFIG @@ -36,7 +37,11 @@ pub async fn update_playlists_daemon( )); ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut failures = super::Failures::default(); loop { + // the first tick completes straight away + ticker.tick().await; + let records_res = sqlx::query_as!(TrackedPlaylist, "SELECT * FROM \"tracked_playlist\"") .fetch_all(&database) .await; @@ -44,22 +49,43 @@ pub async fn update_playlists_daemon( match records_res { Ok(records) => { for record in records { - if let Err(e) = update_playlist(media_client.clone(), record).await { - warn!("Could not update playlist: {:?}", e); + let key = record.id.to_string(); + let about = format!( + "tracked playlist {} (top {}, {}, {})", + record + .playlist_id + .as_deref() + .unwrap_or("without a playlist"), + record.playlist_size, + record.tracking_type, + record.tracking_user + ); + match update_playlist(media_client.clone(), record).await { + Ok(()) => failures.succeeded(&key, &about), + // expected at the start of a period, so not worth a warning + Err(e) + if matches!( + e.downcast_ref(), + Some(ListenbrainzError::NoStats { .. }) + ) => + { + debug!("Skipped {}: {}", about, e) + } + Err(e) => { + failures.failed(&key, format!("Could not update {}: {}", about, e)) + } } } } Err(e) => { - println!("Could not fetch tracked_playlists: {:?}", e); + error!("Could not fetch tracked playlists: {}", e); } } - - ticker.tick().await; } } -async fn update_playlist( +pub async fn update_playlist( media_client: impl AsRef, playlist: TrackedPlaylist, ) -> Result<(), Box> { @@ -127,7 +153,8 @@ async fn update_playlist( tracks.push(track.id); } None => { - error!( + // songs that aren't in the library are expected + debug!( "Couldn't find matching track for {} - {}", recording.track_name, recording.artist_name ) diff --git a/src/discover.rs b/src/discover.rs new file mode 100644 index 0000000..0eb03a5 --- /dev/null +++ b/src/discover.rs @@ -0,0 +1,212 @@ +//! Find songs that aren't in the library to suggest alongside each mix. +//! +//! Candidates come from Listenbrainz's collaborative filtering recommendations +//! for the user (filtered to recordings they've never listened to) and, if a +//! Listenbrainz token is saved to the account (or configured), an LB Radio prompt built from each mix's +//! top genres. Every candidate's MusicBrainz genres are compared with each +//! mix's genre profile (cosine similarity) and it's assigned to the mix it fits +//! best. Songs already in the library, or played recently, are skipped. + +use crate::listenbrainz::{self, RecordingInfo}; +use crate::mix::{name_key, normalize, RecentlyPlayed}; +use crate::subsonic::Subsonic; +use std::collections::{HashMap, HashSet}; +use uuid::Uuid; + +/// Candidates must fit a mix at least this well (cosine similarity of genres) +const MIN_FIT: f64 = 0.2; +/// Most suggestions per artist in one mix +const PER_ARTIST: usize = 2; +/// Recommendations to request from Listenbrainz +const RECOMMENDATIONS: usize = 1000; +/// Genres per LB Radio prompt +const RADIO_GENRES: usize = 3; + +pub struct MixTarget { + pub mix_id: Uuid, + /// The mix's genres (as in the cluster profile, best first) and their weights + pub profile: Vec<(String, f64)>, +} + +pub struct Suggestion { + pub mix_id: Uuid, + pub mbid: String, + pub info: RecordingInfo, + pub score: f64, +} + +/// Cosine similarity between a recording's genres and a mix profile +fn fit(genres: &HashMap, profile: &HashMap, profile_norm: f64) -> f64 { + let (mut dot, mut norm) = (0.0, 0.0); + for (genre, w) in genres { + norm += w * w; + if let Some(p) = profile.get(&normalize(genre)) { + dot += w * p; + } + } + if norm == 0.0 || profile_norm == 0.0 { + 0.0 + } else { + dot / (norm.sqrt() * profile_norm) + } +} + +pub async fn suggest( + client: &Subsonic, + user: &str, + targets: &[MixTarget], + recently_played: &RecentlyPlayed, + // recordings that already have a suggestion the user acted on + exclude: &HashSet, + per_mix: usize, + // a Listenbrainz user token, to also ask LB Radio for candidates + token: Option, +) -> Result, Box> { + if targets.is_empty() || per_mix == 0 { + return Ok(vec![]); + } + + // ---- candidates ---- + let mut candidates: Vec = listenbrainz::recommendations(user, RECOMMENDATIONS) + .await? + .into_iter() + .filter(|r| r.latest_listened_at.is_none()) + .map(|r| r.recording_mbid) + .collect(); + + if let Some(token) = token { + for target in targets { + let genres: Vec<&str> = target + .profile + .iter() + .take(RADIO_GENRES) + .map(|(g, _)| g.as_str()) + .collect(); + // LB Radio prompts can't contain these + if genres.iter().any(|g| g.contains([',', '(', ')', ':'])) { + continue; + } + let prompt = format!("tag:({})::or", genres.join(", ")); + match listenbrainz::radio(&prompt, "medium", &token).await { + Ok(mbids) => candidates.extend(mbids), + Err(e) => log::warn!("LB Radio failed for {}: {}", prompt, e), + } + } + } + + let mut seen = HashSet::new(); + candidates.retain(|m| !exclude.contains(m) && seen.insert(m.clone())); + let metadata = listenbrainz::recording_metadata(&candidates).await?; + + // ---- assign each candidate to the mix it fits best ---- + let profiles: Vec<(HashMap, f64)> = targets + .iter() + .map(|t| { + let mut p: HashMap = HashMap::new(); + for (genre, w) in &t.profile { + *p.entry(normalize(genre)).or_default() += w; + } + let norm = p.values().map(|w| w * w).sum::().sqrt(); + (p, norm) + }) + .collect(); + + let mut per_target: Vec> = vec![vec![]; targets.len()]; + for (mbid, info) in &metadata { + if info.title.is_empty() + || recently_played.contains_recording(Some(mbid), &info.artist, &info.title) + { + continue; + } + let best = profiles + .iter() + .enumerate() + .map(|(i, (p, n))| (i, fit(&info.genres, p, *n))) + .max_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((i, score)) = best { + if score >= MIN_FIT { + per_target[i].push((score, mbid, info)); + } + } + } + + // ---- pick the best per mix, skipping songs already in the library ---- + let mut suggestions = vec![]; + let mut seen_names: HashSet = HashSet::new(); + for (target, mut found) in targets.iter().zip(per_target) { + found.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1))); + let mut artists: HashMap = HashMap::new(); + let mut taken = 0; + + for (score, mbid, info) in found { + if taken >= per_mix { + break; + } + let artist_count = artists.entry(normalize(&info.artist)).or_default(); + if *artist_count >= PER_ARTIST + || seen_names.contains(&name_key(&info.artist, &info.title)) + { + continue; + } + if in_library(client, mbid, info).await? { + continue; + } + + *artist_count += 1; + taken += 1; + seen_names.insert(name_key(&info.artist, &info.title)); + suggestions.push(Suggestion { + mix_id: target.mix_id, + mbid: mbid.clone(), + info: RecordingInfo { + title: info.title.clone(), + artist: info.artist.clone(), + release: info.release.clone(), + cover_url: info.cover_url.clone(), + genres: HashMap::new(), + }, + score, + }); + } + } + + Ok(suggestions) +} + +async fn in_library( + client: &Subsonic, + mbid: &str, + info: &RecordingInfo, +) -> Result> { + if !client.song_search(mbid.to_string()).await?.is_empty() { + return Ok(true); + } + let key = name_key(&info.artist, &info.title); + Ok(client + .song_search(format!("{} {}", info.title, info.artist)) + .await? + .iter() + .any(|s| name_key(&s.artist, &s.title) == key)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fit_prefers_matching_genres() { + let profile: HashMap = + [("mathcore".to_string(), 2.0), ("mathrock".to_string(), 1.0)].into(); + let norm = 5f64.sqrt(); + let math: HashMap = [ + ("Mathcore".to_string(), 1.0), + ("math rock".to_string(), 1.0), + ] + .into(); + let folk: HashMap = [("folk".to_string(), 1.0)].into(); + + assert!(fit(&math, &profile, norm) > 0.9); + assert_eq!(fit(&folk, &profile, norm), 0.0); + assert_eq!(fit(&HashMap::new(), &profile, norm), 0.0); + } +} diff --git a/src/listenbrainz.rs b/src/listenbrainz.rs index 3617d91..6325456 100644 --- a/src/listenbrainz.rs +++ b/src/listenbrainz.rs @@ -1,5 +1,26 @@ use serde::Deserialize; +use std::collections::HashMap; use std::fmt::Display; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum ListenbrainzError { + #[error("Listenbrainz user \"{0}\" doesn't exist")] + UserNotFound(String), + #[error("Listenbrainz has no stats for {user} for {range} yet")] + NoStats { user: String, range: &'static str }, + #[error("Listenbrainz request failed: {0}")] + Http(#[from] reqwest::Error), +} + +/// Requests about a user fail with 404 if the user doesn't exist +fn user_error(user: &str, e: reqwest::Error) -> ListenbrainzError { + if e.status() == Some(reqwest::StatusCode::NOT_FOUND) { + ListenbrainzError::UserNotFound(user.to_string()) + } else { + ListenbrainzError::Http(e) + } +} const BASE: &'static str = "https://api.listenbrainz.org/1"; @@ -48,6 +69,21 @@ impl StatsRange { } } + /// e.g. "last month", for messages + pub fn description(&self) -> &'static str { + match self { + StatsRange::ThisWeek => "this week", + StatsRange::ThisMonth => "this month", + StatsRange::ThisYear => "this year", + StatsRange::Week => "last week", + StatsRange::Month => "last month", + StatsRange::Quarter => "last quarter", + StatsRange::HalfYear => "the last six months", + StatsRange::Year => "last year", + StatsRange::All => "all time", + } + } + pub fn from_param(range: &str) -> Option { match range { "this_week" => Some(StatsRange::ThisWeek), @@ -92,7 +128,8 @@ pub async fn recordings( user: impl Display, range: StatsRange, count: i32, -) -> Result { +) -> Result { + let user = user.to_string(); let url = format!( "{}/stats/user/{}/{}?range={}&count={}", BASE, @@ -102,9 +139,426 @@ pub async fn recordings( count ); - Ok(reqwest::get(url) - .await? - .json::() - .await? - .payload) + let response = reqwest::Client::new() + .get(url) + .header(reqwest::header::USER_AGENT, USER_AGENT) + .send() + .await?; + match response.status() { + reqwest::StatusCode::NOT_FOUND => Err(ListenbrainzError::UserNotFound(user)), + // stats are calculated periodically, so a new period starts out empty + reqwest::StatusCode::NO_CONTENT => Err(ListenbrainzError::NoStats { + user, + range: range.description(), + }), + _ => Ok(response + .error_for_status()? + .json::() + .await? + .payload), + } +} + +const USER_AGENT: &str = concat!("playlistd/", env!("CARGO_PKG_VERSION")); +const LISTENS_PAGE: usize = 1000; +const METADATA_BATCH: usize = 200; + +/// Send a request, waiting out Listenbrainz rate limits and retrying server errors. +async fn send_json( + request: reqwest::RequestBuilder, +) -> Result { + let mut attempt = 0; + loop { + let response = request + .try_clone() + .expect("request bodies are not streamed") + .header(reqwest::header::USER_AGENT, USER_AGENT) + .send() + .await?; + let status = response.status(); + let reset_in = response + .headers() + .get("X-RateLimit-Reset-In") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(1.0); + + if (status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error()) + && attempt < 6 + { + attempt += 1; + let wait = if status.is_server_error() { + 2f64.powi(attempt) + } else { + reset_in + 0.5 + }; + tokio::time::sleep(std::time::Duration::from_secs_f64(wait)).await; + continue; + } + + let remaining = response.headers().get("X-RateLimit-Remaining").cloned(); + let body = response.error_for_status()?.json::().await?; + if remaining.as_ref().and_then(|v| v.to_str().ok()) == Some("0") { + tokio::time::sleep(std::time::Duration::from_secs_f64(reset_in + 0.2)).await; + } + return Ok(body); + } +} + +#[derive(Deserialize)] +struct ListensResponse { + payload: ListensPayload, +} + +#[derive(Deserialize)] +struct ListensPayload { + listens: Vec, +} + +#[derive(Deserialize, Clone)] +pub struct Listen { + pub listened_at: i64, + pub track_metadata: TrackMetadata, +} + +#[derive(Deserialize, Clone)] +pub struct TrackMetadata { + pub artist_name: String, + pub track_name: String, + // Free-form and submitted by clients, so don't trust the field types + #[serde(default)] + pub additional_info: Option, + #[serde(default)] + pub mbid_mapping: Option, +} + +#[derive(Deserialize, Clone)] +pub struct MbidMapping { + #[serde(default)] + pub recording_mbid: Option, +} + +impl Listen { + /// The recording MBID, preferring Listenbrainz's own mapping over the submitting client's + pub fn recording_mbid(&self) -> Option { + self.track_metadata + .mbid_mapping + .as_ref() + .and_then(|m| m.recording_mbid.clone()) + .or_else(|| { + self.track_metadata + .additional_info + .as_ref()? + .get("recording_mbid")? + .as_str() + .map(str::to_string) + }) + .filter(|m| !m.is_empty()) + } +} + +/// All of a user's listens at or after `min_ts`, newest first +pub async fn listens_since( + user: impl Display, + min_ts: i64, +) -> Result, ListenbrainzError> { + let user = user.to_string(); + let client = reqwest::Client::new(); + let mut listens: Vec = vec![]; + let mut max_ts: Option = None; + + loop { + let mut request = client + .get(format!("{}/user/{}/listens", BASE, user)) + .query(&[("count", LISTENS_PAGE as i64)]); + if let Some(max_ts) = max_ts { + request = request.query(&[("max_ts", max_ts)]); + } + + let page = send_json::(request) + .await + .map_err(|e| user_error(&user, e))? + .payload + .listens; + let Some(oldest) = page.last().map(|l| l.listened_at) else { + break; + }; + listens.extend(page.into_iter().filter(|l| l.listened_at >= min_ts)); + if oldest < min_ts || Some(oldest) == max_ts { + break; + } + // max_ts is exclusive + max_ts = Some(oldest); + } + + Ok(listens) +} + +#[derive(Deserialize, Default)] +struct RecordingMetadata { + #[serde(default)] + recording: Option, + #[serde(default)] + artist: Option, + #[serde(default)] + release: Option, + #[serde(default)] + tag: Option, +} + +#[derive(Deserialize, Default)] +struct Named { + #[serde(default)] + name: String, +} + +#[derive(Deserialize, Default)] +struct Release { + #[serde(default)] + name: Option, + #[serde(default)] + caa_id: Option, + #[serde(default)] + caa_release_mbid: Option, +} + +#[derive(Deserialize, Default)] +struct RecordingTags { + #[serde(default)] + recording: Vec, + #[serde(default)] + release_group: Vec, + #[serde(default)] + artist: Vec, +} + +#[derive(Deserialize)] +struct Tag { + tag: String, + #[serde(default)] + count: Option, + /// Only set for tags that are MusicBrainz genres (not e.g. "british" or "female vocals") + #[serde(default)] + genre_mbid: Option, +} + +pub struct RecordingInfo { + pub title: String, + pub artist: String, + pub release: Option, + /// Front cover from the Cover Art Archive, if there is one + pub cover_url: Option, + /// Weighted MusicBrainz genres, combining the recording's own genres (most specific) with + /// those of its release group and artists (broadest). Names are lowercased. + pub genres: HashMap, +} + +/// Names, cover art and genres of recordings +pub async fn recording_metadata( + mbids: &[String], +) -> Result, reqwest::Error> { + let client = reqwest::Client::new(); + let mut out = HashMap::new(); + + for batch in mbids.chunks(METADATA_BATCH) { + let request = + client + .post(format!("{}/metadata/recording/", BASE)) + .json(&serde_json::json!({ + "recording_mbids": batch, + "inc": "artist tag release", + })); + let metadata = send_json::>(request).await?; + + for (mbid, recording) in metadata { + let mut genres: HashMap = HashMap::new(); + if let Some(tags) = &recording.tag { + for (source, weight) in [ + (&tags.recording, 3.0), + (&tags.release_group, 2.0), + (&tags.artist, 1.0), + ] { + for tag in source.iter().filter(|t| t.genre_mbid.is_some()) { + let name = tag.tag.trim().to_lowercase(); + if !name.is_empty() { + *genres.entry(name).or_default() += + weight * (1.0 + tag.count.unwrap_or(1).max(1) as f64).ln(); + } + } + } + } + let release = recording.release.unwrap_or_default(); + let cover_url = match (release.caa_id, &release.caa_release_mbid) { + (Some(id), Some(release_mbid)) => Some(format!( + "https://coverartarchive.org/release/{}/{}-250.jpg", + release_mbid, id + )), + _ => None, + }; + + out.insert( + mbid, + RecordingInfo { + title: recording.recording.unwrap_or_default().name, + artist: recording.artist.unwrap_or_default().name, + release: release.name, + cover_url, + genres, + }, + ); + } + } + + Ok(out) +} + +/// Weighted MusicBrainz genres for each recording; see [`RecordingInfo::genres`] +pub async fn recording_tags( + mbids: &[String], +) -> Result>, reqwest::Error> { + Ok(recording_metadata(mbids) + .await? + .into_iter() + .map(|(mbid, info)| (mbid, info.genres)) + .collect()) +} + +#[derive(Deserialize)] +struct RecommendationsResponse { + payload: RecommendationsPayload, +} + +#[derive(Deserialize)] +struct RecommendationsPayload { + #[serde(default)] + mbids: Vec, +} + +#[derive(Deserialize, Clone)] +pub struct Recommendation { + pub recording_mbid: String, + /// Set if the user has ever listened to the recording + #[serde(default)] + pub latest_listened_at: Option, +} + +/// Listenbrainz's collaborative filtering recording recommendations for a user +pub async fn recommendations( + user: impl Display, + count: usize, +) -> Result, ListenbrainzError> { + let user = user.to_string(); + let response = reqwest::Client::new() + .get(format!( + "{}/cf/recommendation/user/{}/recording", + BASE, user + )) + .query(&[("count", count)]) + .header(reqwest::header::USER_AGENT, USER_AGENT) + .send() + .await? + .error_for_status() + .map_err(|e| user_error(&user, e))?; + + // 204 when there are no recommendations for the user (yet) + if response.status() == reqwest::StatusCode::NO_CONTENT { + return Ok(vec![]); + } + Ok(response + .json::() + .await? + .payload + .mbids) +} + +/// The user token needed by some endpoints (e.g. LB Radio): the one saved to the account in the +/// web UI, or otherwise `listenbrainz.token` from the config +pub async fn token(database: &sqlx::PgPool) -> Option { + match sqlx::query_scalar!( + r#" + SELECT listenbrainz_token AS "token!" FROM "app_user" + WHERE listenbrainz_token IS NOT NULL + ORDER BY created_at + LIMIT 1 + "# + ) + .fetch_optional(database) + .await + { + Ok(Some(token)) => return Some(token), + Ok(None) => {} + Err(e) => log::warn!("Could not load the account's Listenbrainz token: {}", e), + } + crate::CONFIG + .get()? + .get::("listenbrainz.token") + .ok() + .filter(|t| !t.is_empty()) +} + +#[derive(Deserialize)] +struct ValidateTokenResponse { + valid: bool, + user_name: Option, +} + +/// The name of the Listenbrainz user a token belongs to, or `None` if it isn't valid +pub async fn validate_token(token: &str) -> Result, reqwest::Error> { + let request = reqwest::Client::new() + .get(format!("{}/validate-token", BASE)) + .header(reqwest::header::AUTHORIZATION, format!("Token {}", token)); + let response = send_json::(request).await?; + Ok(response.user_name.filter(|_| response.valid)) +} + +#[derive(Deserialize)] +struct RadioResponse { + payload: RadioPayload, +} + +#[derive(Deserialize)] +struct RadioPayload { + jspf: Jspf, +} + +#[derive(Deserialize)] +struct Jspf { + playlist: JspfPlaylist, +} + +#[derive(Deserialize)] +struct JspfPlaylist { + #[serde(default)] + track: Vec, +} + +#[derive(Deserialize)] +struct JspfTrack { + #[serde(default)] + identifier: Vec, +} + +/// Recording MBIDs from an LB Radio prompt, e.g. `tag:(mathcore, math rock)::or`. +/// `mode` is "easy", "medium" or "hard" (more obscure). Needs a user token. +pub async fn radio(prompt: &str, mode: &str, token: &str) -> Result, reqwest::Error> { + let request = reqwest::Client::new() + .get(format!("{}/explore/lb-radio", BASE)) + .query(&[("prompt", prompt), ("mode", mode)]) + .header(reqwest::header::AUTHORIZATION, format!("Token {}", token)); + + Ok(send_json::(request) + .await? + .payload + .jspf + .playlist + .track + .into_iter() + .flat_map(|t| t.identifier) + .filter_map(|id| { + id.rsplit('/') + .next() + .filter(|m| m.len() == 36) + .map(str::to_string) + }) + .collect()) } diff --git a/src/main.rs b/src/main.rs index e469947..3cb42c1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,13 +1,22 @@ +mod auth; +mod cluster; mod daemon; +mod discover; mod listenbrainz; +mod mix; mod models; mod playlist; mod subsonic; mod track; +mod tracked; +mod web; +mod youtube; -use crate::daemon::{create_playlists_daemon, update_playlists_daemon}; +use crate::auth::User; +use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon}; use crate::models::{ - CreateTrackedPlaylist, PartialCreateTrackedPlaylist, PartialTrackedPlaylist, TrackedPlaylist, + ClusterMixRule, CreateTrackedPlaylist, PartialClusterMixRule, PartialCreateTrackedPlaylist, + PartialTrackedPlaylist, TrackedPlaylist, }; use crate::subsonic::{Subsonic, SubsonicBuilder}; use config::Config; @@ -31,6 +40,8 @@ async fn main() -> Result<(), Box> { ) .unwrap(); + init_logging(CONFIG.get().unwrap()); + let database = PgPool::connect( CONFIG .get() @@ -52,19 +63,44 @@ async fn main() -> Result<(), Box> { { let _media_client = media_client.clone(); tokio::spawn(async move { - update_playlists_daemon(_media_client).await.unwrap(); + if let Err(e) = update_playlists_daemon(_media_client).await { + log::error!("Tracked playlist daemon stopped: {}", e); + } }); } { let _media_client = media_client.clone(); tokio::spawn(async move { - create_playlists_daemon(_media_client).await.unwrap(); + if let Err(e) = create_playlists_daemon(_media_client).await { + log::error!("Playlist rule daemon stopped: {}", e); + } + }); + } + { + let _media_client = media_client.clone(); + tokio::spawn(async move { + if let Err(e) = cluster_mixes_daemon(_media_client).await { + log::error!("Cluster mix daemon stopped: {}", e); + } }); } - rocket::build() + let youtube = youtube::YouTube::new( + CONFIG + .get() + .unwrap() + .get::("discover.ytdlp") + .unwrap_or_else(|_| "yt-dlp".to_string()), + ); + + let mut server = rocket::build() .manage(media_client) .manage(database) + .manage(youtube) + .mount("/api/auth", auth::routes()) + .register("/api", rocket::catchers![auth::unauthorized]) + .mount("/api/discover", web::routes()) + .mount("/api/tracked", tracked::routes()) .mount( "/api/playlist", routes![ @@ -72,14 +108,78 @@ async fn main() -> Result<(), Box> { add_tracking_playlist, all_playlists, create_tracking_playlist_rule, + create_cluster_mix_rule, + all_cluster_mix_rules, ], - ) - .launch() - .await?; + ); + + // the discover UI's built files (discover/dist) + if let Ok(ui) = CONFIG.get().unwrap().get::("discover.ui") { + // Rocket panics if the directory doesn't exist + if std::path::Path::new(&ui).is_dir() { + server = server.mount("/", rocket::fs::FileServer::from(ui)); + } else { + log::warn!( + "Not serving the web UI: {} doesn't exist. Build it with `npm run build` in discover/", + ui + ); + } + } + + server.launch().await?; Ok(()) } +/// Log to stdout at `log.level` (default "info"). RUST_LOG overrides it, e.g. +/// `RUST_LOG=playlistd=debug,sqlx=info`. +fn init_logging(config: &Config) { + use log::LevelFilter; + use std::io::Write; + + let configured = config.get::("log.level").ok(); + let level = configured + .as_deref() + .and_then(|l| l.parse::().ok()) + .unwrap_or(LevelFilter::Info); + + let mut builder = env_logger::Builder::new(); + builder.filter_level(level); + // Rocket logs every request at info; keep its warnings and launch messages + builder.filter_module("rocket", level.min(LevelFilter::Warn)); + // sqlx logs Postgres notices (e.g. from migrations) at info + builder.filter_module("sqlx", level.min(LevelFilter::Warn)); + // libraries that are very chatty at debug + for module in ["hyper", "hyper_util", "reqwest", "rustls", "h2"] { + builder.filter_module(module, level.min(LevelFilter::Info)); + } + builder.parse_env("RUST_LOG"); + + // Under systemd, tag lines with their priority so `journalctl -p warning` works. + // journald adds its own timestamps. + if std::env::var_os("JOURNAL_STREAM").is_some() { + builder.format(|buf, record| { + let priority = match record.level() { + log::Level::Error => 3, + log::Level::Warn => 4, + log::Level::Info => 6, + log::Level::Debug | log::Level::Trace => 7, + }; + writeln!(buf, "<{}>{}: {}", priority, record.target(), record.args()) + }); + } + builder.init(); + + if let Some(configured) = configured { + if configured.parse::().is_err() { + log::warn!( + "Unknown log.level {:?}; use error, warn, info, debug or trace", + configured + ); + } + } +} + #[derive(Serialize)] struct JsonError { error: String, @@ -118,6 +218,7 @@ pub struct CreatePlaylist { /// Create a new playlist and attach a tracker #[post("/rule", data = "")] async fn create_tracking_playlist_rule( + _user: User, pool: &State, create_playlist_rule: Json, ) -> Json> { @@ -130,6 +231,7 @@ async fn create_tracking_playlist_rule( /// Create a new playlist and attach a tracker #[post("/create", data = "")] async fn create_tracking_playlist( + _user: User, media_client: &State>, pool: &State, create_playlist: Json, @@ -161,6 +263,7 @@ async fn create_tracking_playlist( /// Add tracking to an existing playlist #[post("/track", data = "")] async fn add_tracking_playlist( + _user: User, pool: &State, playlist: Json, ) -> Json> { @@ -172,9 +275,31 @@ async fn add_tracking_playlist( /// Get all tracked playlists #[get("/")] -async fn all_playlists(pool: &State) -> JsonValue { +async fn all_playlists(_user: User, pool: &State) -> JsonValue { match TrackedPlaylist::all(pool.inner()).await { Ok(playlists) => json!(playlists), Err(_) => json!([]), } } + +/// Create a rule that maintains genre mixes built from clustering a user's recent listens +#[post("/mix", data = "")] +async fn create_cluster_mix_rule( + _user: User, + pool: &State, + rule: Json, +) -> Json> { + match rule.record(pool.inner()).await { + Ok(rule) => Json(Response::Success(rule)), + Err(e) => Json(Response::Error(e.into())), + } +} + +/// Get all cluster mix rules +#[get("/mix")] +async fn all_cluster_mix_rules(_user: User, pool: &State) -> JsonValue { + match ClusterMixRule::all(pool.inner()).await { + Ok(rules) => json!(rules), + Err(_) => json!([]), + } +} diff --git a/src/mix.rs b/src/mix.rs new file mode 100644 index 0000000..f62bc72 --- /dev/null +++ b/src/mix.rs @@ -0,0 +1,345 @@ +//! Turn a cluster of listened tracks into a playlist of library songs. +//! +//! The cluster's tag profile is matched against the Subsonic library's genres. +//! Songs from the best matching genres are scored by how well their own genres +//! fit the profile, and the mix is made of: +//! * "familiar" tracks: the cluster's most played tracks, if they're in the library +//! * "discovery" tracks: well-fitting songs that weren't played recently, sampled +//! at random (weighted by fit) with a cap on songs per artist + +use crate::cluster::Cluster; +use crate::subsonic::{Subsonic, SubsonicError}; +use crate::track::Track; +use rand::rngs::StdRng; +use rand::seq::SliceRandom; +use rand::Rng; +use std::collections::{HashMap, HashSet}; + +pub struct MixOptions { + pub size: usize, + /// Share of the mix taken from the cluster's recently played tracks + pub familiar_ratio: f64, + /// How many library genres to draw songs from + pub max_genres: usize, + /// Most songs to consider from each genre + pub songs_per_genre: usize, +} + +pub struct Mix { + pub label: String, + /// Library genres describing the mix, best first + pub tags: Vec, + pub song_ids: Vec, + /// The songs in the mix that were played recently + pub known_song_ids: Vec, +} + +/// A track from the listening history +pub struct ListenedTrack { + pub mbid: Option, + pub artist: String, + pub title: String, +} + +/// Lowercase alphanumerics only, so "Post-Hardcore" matches "post hardcore" +pub fn normalize(s: &str) -> String { + s.chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(char::to_lowercase) + .collect() +} + +pub fn name_key(artist: &str, title: &str) -> String { + format!("{}\u{1f}{}", normalize(artist), normalize(title)) +} + +/// Tracks played during the clustered period, for telling "discovery" songs apart +#[derive(Default)] +pub struct RecentlyPlayed { + mbids: HashSet, + names: HashSet, +} + +impl RecentlyPlayed { + pub fn insert(&mut self, track: &ListenedTrack) { + if let Some(mbid) = &track.mbid { + self.mbids.insert(mbid.clone()); + } + self.names.insert(name_key(&track.artist, &track.title)); + } + + fn contains(&self, song: &Track) -> bool { + self.contains_recording(song.music_brainz_id.as_deref(), &song.artist, &song.title) + } + + pub fn contains_recording(&self, mbid: Option<&str>, artist: &str, title: &str) -> bool { + mbid.is_some_and(|m| self.mbids.contains(m)) + || self.names.contains(&name_key(artist, title)) + } +} + +/// Library genres by normalised name +pub fn genre_index(genres: impl IntoIterator) -> HashMap { + let mut index = HashMap::new(); + for genre in genres { + let key = normalize(&genre); + if !key.is_empty() { + index.entry(key).or_insert(genre); + } + } + index +} + +#[derive(Default)] +struct Selection { + songs: Vec, + ids: HashSet, + artists: HashMap, +} + +impl Selection { + fn take(&mut self, song: Track) { + if self.ids.insert(song.id.clone()) { + *self.artists.entry(normalize(&song.artist)).or_default() += 1; + self.songs.push(song); + } + } + + fn artist_count(&self, artist: &str) -> usize { + self.artists.get(&normalize(artist)).copied().unwrap_or(0) + } +} + +pub async fn build_mix( + client: &Subsonic, + cluster: &Cluster, + library_genres: &HashMap, + listened: &HashMap, + recently_played: &RecentlyPlayed, + opts: &MixOptions, + rng: &mut StdRng, +) -> Result, SubsonicError> { + // ---- match the cluster's profile to library genres ---- + let mut weights: HashMap = HashMap::new(); + for (tag, score) in &cluster.profile { + *weights.entry(normalize(tag)).or_default() += score; + } + let mut matched: Vec<(String, f64)> = vec![]; + for (tag, _) in &cluster.profile { + let key = normalize(tag); + if library_genres.contains_key(&key) && !matched.iter().any(|(k, _)| *k == key) { + matched.push((key.clone(), weights[&key])); + } + } + matched.truncate(opts.max_genres); + if matched.is_empty() { + return Ok(None); + } + + // ---- candidate songs ---- + let mut pool: HashMap = HashMap::new(); + for (key, _) in &matched { + for song in client + .songs_by_genre(&library_genres[key], opts.songs_per_genre) + .await? + { + pool.entry(song.id.clone()).or_insert(song); + } + } + + let score = |song: &Track| -> f64 { + let genres = song.genre_names(); + if genres.is_empty() { + return 0.0; + } + let fit: f64 = genres + .iter() + .filter_map(|g| weights.get(&normalize(g))) + .sum(); + // don't let songs tagged with every genre under the sun dominate + fit / (genres.len() as f64).sqrt() + }; + + let by_mbid: HashMap<&str, &Track> = pool + .values() + .filter_map(|s| Some((s.music_brainz_id.as_deref()?, s))) + .filter(|(m, _)| !m.is_empty()) + .collect(); + let by_name: HashMap = pool + .values() + .map(|s| (name_key(&s.artist, &s.title), s)) + .collect(); + + let mut selection = Selection::default(); + let artist_cap = (opts.size / 8).max(2); + + // ---- familiar: the cluster's most played tracks ---- + let familiar_quota = + ((opts.size as f64) * opts.familiar_ratio.clamp(0.0, 1.0)).round() as usize; + for (key, _) in cluster.tracks.iter().take(familiar_quota * 4) { + if selection.songs.len() >= familiar_quota { + break; + } + let Some(track) = listened.get(key) else { + continue; + }; + if selection.artist_count(&track.artist) >= artist_cap { + continue; + } + let found = match track + .mbid + .as_deref() + .and_then(|m| by_mbid.get(m)) + .or_else(|| by_name.get(&name_key(&track.artist, &track.title))) + { + Some(song) => Some((*song).clone()), + // it may be in the library under a genre we didn't pull + None => match &track.mbid { + Some(mbid) => { + let results = client.song_search(mbid.clone()).await?; + if results.len() == 1 { + results.into_iter().next() + } else { + None + } + } + None => None, + }, + }; + if let Some(song) = found { + selection.take(song); + } + } + + let known_song_ids: Vec = selection.songs.iter().map(|s| s.id.clone()).collect(); + + // ---- discovery: weighted random sample of well-fitting songs ---- + // Efraimidis-Spirakis: sort by u^(1/w) to sample without replacement, weighted by w + let mut ranked: Vec<(f64, &Track)> = pool + .values() + .filter_map(|song| { + let s = score(song); + (s > 0.0).then(|| (rng.gen::().powf(1.0 / (s * s)), song)) + }) + .collect(); + ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.id.cmp(&b.1.id))); + + // relax the rules in passes if the library is too small to fill the mix + for (allow_recent, cap_artists) in [(false, true), (true, true), (true, false)] { + for (_, song) in &ranked { + if selection.songs.len() >= opts.size { + break; + } + if selection.ids.contains(&song.id) + || (!allow_recent && recently_played.contains(song)) + || (cap_artists && selection.artist_count(&song.artist) >= artist_cap) + { + continue; + } + selection.take((*song).clone()); + } + } + + let mut chosen = selection.songs; + if chosen.is_empty() { + return Ok(None); + } + chosen.shuffle(rng); + + let label = matched + .iter() + .take(3) + .map(|(key, _)| library_genres[key].clone()) + .collect::>() + .join(" / "); + + Ok(Some(Mix { + label, + tags: matched + .iter() + .take(5) + .map(|(k, _)| library_genres[k].clone()) + .collect(), + song_ids: chosen.into_iter().map(|s| s.id).collect(), + known_song_ids, + })) +} + +/// Pair up previous mixes with new ones by genre overlap, so that playlists keep their identity +/// across rebuilds. Returns `(old index, new index)` pairs. +pub fn match_mixes(old: &[Vec], new: &[Vec]) -> Vec<(usize, usize)> { + let mut pairs: Vec<(f64, usize, usize)> = vec![]; + for (i, a) in old.iter().enumerate() { + for (j, b) in new.iter().enumerate() { + let a: HashSet = a.iter().map(|t| normalize(t)).collect(); + let b: HashSet = b.iter().map(|t| normalize(t)).collect(); + let union = a.union(&b).count(); + let jaccard = if union == 0 { + 0.0 + } else { + a.intersection(&b).count() as f64 / union as f64 + }; + if jaccard > 0.0 { + pairs.push((jaccard, i, j)); + } + } + } + pairs.sort_by(|a, b| b.0.total_cmp(&a.0).then((a.1, a.2).cmp(&(b.1, b.2)))); + + let (mut used_old, mut used_new) = (HashSet::new(), HashSet::new()); + let mut matched = vec![]; + for (_, i, j) in pairs { + if !used_old.contains(&i) && !used_new.contains(&j) { + used_old.insert(i); + used_new.insert(j); + matched.push((i, j)); + } + } + matched +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tags(t: &[&str]) -> Vec { + t.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn normalizes_genre_names() { + assert_eq!(normalize("Post-Hardcore"), normalize("post hardcore")); + assert_eq!(normalize("Drum & Bass"), "drumbass"); + let index = genre_index(["Pop Punk".to_string(), "pop-punk".to_string()]); + assert_eq!(index.len(), 1); + assert_eq!(index["poppunk"], "Pop Punk"); + } + + #[test] + fn matches_mixes_by_overlap() { + let old = vec![ + tags(&["metal", "deathmetal"]), + tags(&["folk"]), + tags(&["jazz"]), + ]; + let new = vec![ + tags(&["folk", "indiefolk"]), + tags(&["metal", "blackmetal"]), + tags(&["pop"]), + ]; + let mut m = match_mixes(&old, &new); + m.sort(); + assert_eq!(m, vec![(0, 1), (1, 0)]); + } + + #[test] + fn genre_names_fall_back_to_genre_field() { + let mut track: Track = serde_json::from_value(serde_json::json!({ + "id": "1", "title": "t", "genre": "Rock; Indie Rock" + })) + .unwrap(); + assert_eq!(track.genre_names(), vec!["Rock", "Indie Rock"]); + track.genres = vec![crate::track::ItemGenre { name: "Emo".into() }]; + assert_eq!(track.genre_names(), vec!["Emo"]); + } +} diff --git a/src/models.rs b/src/models.rs index c0dded5..0204099 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,3 +1,4 @@ +use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sqlx::error::Error; use sqlx::{Executor, Postgres}; @@ -131,3 +132,120 @@ impl CreateTrackedPlaylist { .await } } + +#[derive(Deserialize)] +pub struct PartialClusterMixRule { + pub tracking_user: String, + pub months: Option, + pub cluster_count: Option, + pub playlist_size: Option, + pub familiar_ratio: Option, + pub name_template: Option, + pub refresh_hours: Option, + pub discovery_count: Option, +} + +impl PartialClusterMixRule { + pub async fn record( + &self, + pool: impl Executor<'_, Database = Postgres> + Copy, + ) -> Result { + let uuid = Uuid::new_v4(); + + sqlx::query!( + r#" + INSERT INTO "cluster_mix_rule" + (id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours, discovery_count) + VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24), COALESCE($9, 15)) + "#, + uuid, + self.tracking_user, + self.months, + self.cluster_count, + self.playlist_size, + self.familiar_ratio, + self.name_template, + self.refresh_hours, + self.discovery_count, + ) + .execute(pool) + .await?; + + ClusterMixRule::rule(pool, uuid).await + } +} + +#[derive(Serialize)] +pub struct ClusterMixRule { + pub id: Uuid, + pub tracking_user: String, + pub months: i32, + pub cluster_count: Option, + pub playlist_size: i32, + pub familiar_ratio: f64, + pub name_template: String, + pub refresh_hours: i32, + pub last_run: Option>, + pub discovery_count: i32, +} + +impl ClusterMixRule { + pub async fn all(pool: impl Executor<'_, Database = Postgres>) -> Result, Error> { + sqlx::query_as!(Self, r#"SELECT * FROM "cluster_mix_rule""#) + .fetch_all(pool) + .await + } + + /// Rules whose mixes haven't been built within their refresh interval + pub async fn due(pool: impl Executor<'_, Database = Postgres>) -> Result, Error> { + sqlx::query_as!( + Self, + r#" + SELECT * FROM "cluster_mix_rule" + WHERE last_run IS NULL OR last_run < NOW() - make_interval(hours => refresh_hours) + "# + ) + .fetch_all(pool) + .await + } + + pub async fn rule( + pool: impl Executor<'_, Database = Postgres>, + uuid: Uuid, + ) -> Result { + sqlx::query_as!( + Self, + r#"SELECT * FROM "cluster_mix_rule" WHERE id = $1"#, + uuid + ) + .fetch_one(pool) + .await + } +} + +#[derive(Serialize)] +pub struct ClusterMixPlaylist { + pub id: Uuid, + pub rule_id: Uuid, + pub playlist_id: String, + pub tags: Vec, + pub name: Option, + pub position: i32, + pub known_song_ids: Vec, +} + +#[derive(Serialize)] +pub struct MixSuggestion { + pub id: Uuid, + pub rule_id: Uuid, + pub mix_id: Option, + pub recording_mbid: String, + pub title: String, + pub artist: String, + pub release: Option, + pub cover_url: Option, + pub score: f64, + pub status: String, + pub youtube_id: Option, + pub created_at: DateTime, +} diff --git a/src/subsonic.rs b/src/subsonic.rs index a185511..4aca222 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -43,6 +43,41 @@ struct GetPlaylistResponse { type CreatePlaylistResponse = GetPlaylistResponse; +#[derive(Deserialize)] +struct GetPlaylistsResponse { + playlists: PlaylistList, +} + +#[derive(Deserialize)] +struct PlaylistList { + #[serde(default)] + playlist: Vec, +} + +#[derive(Deserialize)] +struct GetGenresResponse { + genres: GenreList, +} + +#[derive(Deserialize)] +struct GenreList { + #[serde(default)] + genre: Vec, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct Genre { + pub value: String, + #[serde(rename = "songCount", default)] + pub song_count: usize, +} + +#[derive(Deserialize)] +struct SongsByGenreResponse { + #[serde(rename = "songsByGenre")] + songs_by_genre: SearchResponseSongs, +} + struct AuthParams { salt: String, hash: String, @@ -51,11 +86,17 @@ struct AuthParams { #[derive(Debug, Error)] pub enum SubsonicError { Reqwest(reqwest::Error), + Api(String), + Json(serde_json::Error), } impl Display for SubsonicError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + match self { + SubsonicError::Reqwest(e) => write!(f, "Subsonic request failed: {}", e), + SubsonicError::Api(message) => write!(f, "Subsonic said: {}", message), + SubsonicError::Json(e) => write!(f, "Unexpected response from Subsonic: {}", e), + } } } @@ -194,6 +235,161 @@ impl Subsonic { self.get_playlist(playlist_id).await } + + /// Authentication and format parameters common to every request + fn base_params(&self) -> Vec<(&'static str, String)> { + let auth_params = self.auth_params(); + vec![ + ("u", self.username.to_string()), + ("s", auth_params.salt), + ("t", auth_params.hash), + ("v", String::from("16")), + ("c", String::from("playlistd")), + ("f", String::from("json")), + ] + } + + async fn request( + &self, + endpoint: &str, + params: &[(&'static str, String)], + ) -> Result { + let mut query = self.base_params(); + query.extend_from_slice(params); + + let response = self + .client + .get(format!("{}/{}", self.base, endpoint)) + .query(&query) + .send() + .await + .map_err(SubsonicError::Reqwest)? + .json::>() + .await + .map_err(SubsonicError::Reqwest)? + .subsonic_response; + + if response.get("status").and_then(|s| s.as_str()) == Some("failed") { + return Err(SubsonicError::Api( + response + .pointer("/error/message") + .and_then(|m| m.as_str()) + .unwrap_or("unknown error") + .to_string(), + )); + } + serde_json::from_value(response).map_err(SubsonicError::Json) + } + + /// Request a binary endpoint (e.g. `stream`, `getCoverArt`) and hand back the raw response, + /// forwarding an HTTP Range header if given + pub async fn raw( + &self, + endpoint: &str, + params: &[(&'static str, String)], + range: Option<&str>, + ) -> Result { + let mut query = self.base_params(); + query.extend_from_slice(params); + + let mut request = self + .client + .get(format!("{}/{}", self.base, endpoint)) + .query(&query); + if let Some(range) = range { + request = request.header(reqwest::header::RANGE, range); + } + request.send().await.map_err(SubsonicError::Reqwest) + } + + /// All of the user's playlists, without their songs + pub async fn get_playlists(&self) -> Result, SubsonicError> { + Ok(self + .request::("getPlaylists", &[]) + .await? + .playlists + .playlist) + } + + /// All genres in the library + pub async fn get_genres(&self) -> Result, SubsonicError> { + Ok(self + .request::("getGenres", &[]) + .await? + .genres + .genre) + } + + /// Up to `limit` songs with the given genre + pub async fn songs_by_genre( + &self, + genre: &str, + limit: usize, + ) -> Result, SubsonicError> { + // Subsonic caps a single page at 500 + const PAGE: usize = 500; + let mut songs = vec![]; + + while songs.len() < limit { + let count = PAGE.min(limit - songs.len()); + let page = self + .request::( + "getSongsByGenre", + &[ + ("genre", genre.to_string()), + ("count", count.to_string()), + ("offset", songs.len().to_string()), + ], + ) + .await? + .songs_by_genre + .song; + let done = page.len() < count; + songs.extend(page); + if done { + break; + } + } + + Ok(songs) + } + + pub async fn rename_playlist( + &self, + playlist_id: &str, + name: &str, + ) -> Result<(), SubsonicError> { + self.request::( + "updatePlaylist", + &[ + ("playlistId", playlist_id.to_string()), + ("name", name.to_string()), + ], + ) + .await?; + Ok(()) + } + + /// Replace all of a playlist's songs + pub async fn replace_playlist_songs( + &self, + playlist_id: &str, + song_ids: Vec, + ) -> Result { + let playlist = self.get_playlist(playlist_id).await?; + self.update_playlist( + playlist_id.to_string(), + song_ids, + (0..playlist.song_count).collect(), + ) + .await + } + + pub async fn delete_playlist(&self, playlist_id: &str) -> Result<(), SubsonicError> { + self.request::("deletePlaylist", &[("id", playlist_id.to_string())]) + .await?; + Ok(()) + } } #[derive(Default)] diff --git a/src/track.rs b/src/track.rs index 69f9b92..866a690 100644 --- a/src/track.rs +++ b/src/track.rs @@ -4,6 +4,41 @@ use serde::{Deserialize, Serialize}; pub struct Track { pub id: String, pub title: String, + #[serde(default)] pub album: String, + #[serde(default)] pub artist: String, + #[serde(default)] + pub genre: Option, + /// OpenSubsonic: all of the song's genres + #[serde(default)] + pub genres: Vec, + #[serde(rename = "musicBrainzId", default)] + pub music_brainz_id: Option, + /// Seconds + #[serde(default)] + pub duration: Option, + #[serde(rename = "coverArt", default)] + pub cover_art: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct ItemGenre { + pub name: String, +} + +impl Track { + /// The song's genres, from the OpenSubsonic `genres` list if the server provides it, + /// otherwise from the plain `genre` field + pub fn genre_names(&self) -> Vec { + if !self.genres.is_empty() { + return self.genres.iter().map(|g| g.name.clone()).collect(); + } + self.genre + .iter() + .flat_map(|g| g.split([';', ',', '/'])) + .map(|g| g.trim().to_string()) + .filter(|g| !g.is_empty()) + .collect() + } } diff --git a/src/tracked.rs b/src/tracked.rs new file mode 100644 index 0000000..8993a6a --- /dev/null +++ b/src/tracked.rs @@ -0,0 +1,589 @@ +//! API for managing tracked playlists (Subsonic playlists kept up to date with a Listenbrainz +//! user's top songs) and the rules that create them on a schedule. + +use crate::auth::User; +use crate::daemon::update_playlists::update_playlist; +use crate::listenbrainz::StatsRange; +use crate::models::{CreateTrackedPlaylist, TrackedPlaylist}; +use crate::subsonic::Subsonic; +use chrono::format::{Item, StrftimeItems}; +use chrono::Local; +use rocket::http::Status; +use rocket::response::status::Custom; +use rocket::serde::json::Json; +use rocket::{delete, get, post, put, routes, Route, State}; +use serde::{Deserialize, Serialize}; +use sqlx::postgres::PgPool; +use std::collections::HashMap; +use std::sync::Arc; +use uuid::Uuid; + +pub fn routes() -> Vec { + routes![ + playlists, + create_playlist, + update_tracked_playlist, + delete_tracked_playlist, + refresh, + subsonic_playlists, + rules, + create_rule, + update_rule, + delete_rule, + preview_name + ] +} + +#[derive(Serialize)] +pub struct ApiError { + error: String, +} + +type ApiResult = Result, Custom>>; + +fn fail(status: Status, message: impl Into) -> Custom> { + Custom( + status, + Json(ApiError { + error: message.into(), + }), + ) +} + +fn db_error(e: sqlx::Error) -> Custom> { + match e { + sqlx::Error::RowNotFound => fail(Status::NotFound, "Not found"), + e => { + log::error!("Database error: {}", e); + fail(Status::InternalServerError, "Database error") + } + } +} + +fn subsonic_error(e: impl std::fmt::Debug) -> Custom> { + log::error!("Subsonic request failed: {:?}", e); + fail(Status::BadGateway, "Couldn't reach Subsonic") +} + +fn parse_id(id: &str) -> Result>> { + Uuid::parse_str(id).map_err(|_| fail(Status::NotFound, "Not found")) +} + +/// Settings shared by tracked playlists and rules +#[derive(Deserialize)] +struct Tracking { + playlist_size: i32, + tracking_user: String, + tracking_type: String, +} + +impl Tracking { + fn validate(&self) -> Result<(), Custom>> { + if !(1..=1000).contains(&self.playlist_size) { + return Err(fail( + Status::UnprocessableEntity, + "Size must be between 1 and 1000", + )); + } + if self.tracking_user.trim().is_empty() { + return Err(fail( + Status::UnprocessableEntity, + "Enter a Listenbrainz user", + )); + } + if StatsRange::from_param(&self.tracking_type).is_none() { + return Err(fail(Status::UnprocessableEntity, "Unknown time period")); + } + Ok(()) + } +} + +/// Format a playlist name template, or explain why it's invalid +fn format_template(template: &str) -> Result>> { + if template.trim().is_empty() { + return Err(fail(Status::UnprocessableEntity, "Enter a name")); + } + // chrono panics when displaying a format with invalid specifiers + if StrftimeItems::new(template).any(|item| matches!(item, Item::Error)) { + return Err(fail( + Status::UnprocessableEntity, + "The name has an invalid % code (use %% for a literal %)", + )); + } + Ok(Local::now().format(template).to_string()) +} + +// --------------------------------------------------------------------------- +// Tracked playlists +// --------------------------------------------------------------------------- + +#[derive(Serialize)] +struct TrackedPlaylistView { + id: Uuid, + playlist_id: Option, + /// Name in Subsonic; None if the playlist no longer exists there + name: Option, + song_count: Option, + playlist_size: i32, + tracking_user: String, + tracking_type: String, +} + +async fn view( + media_client: &Subsonic, + rows: Vec, +) -> Result, Custom>> { + let subsonic: HashMap = media_client + .get_playlists() + .await + .map_err(subsonic_error)? + .into_iter() + .map(|p| (p.id, (p.name, p.song_count))) + .collect(); + + Ok(rows + .into_iter() + .map(|row| { + let found = row.playlist_id.as_ref().and_then(|id| subsonic.get(id)); + TrackedPlaylistView { + id: row.id, + name: found.map(|(name, _)| name.clone()), + song_count: found.map(|(_, count)| *count), + playlist_id: row.playlist_id, + playlist_size: row.playlist_size, + tracking_user: row.tracking_user, + tracking_type: row.tracking_type, + } + }) + .collect()) +} + +#[get("/playlists")] +async fn playlists( + _user: User, + pool: &State, + media_client: &State>, +) -> ApiResult> { + let mut rows = TrackedPlaylist::all(pool.inner()).await.map_err(db_error)?; + rows.sort_by(|a, b| a.tracking_user.cmp(&b.tracking_user)); + let mut out = view(media_client, rows).await?; + out.sort_by(|a, b| { + a.name + .as_deref() + .unwrap_or("") + .to_lowercase() + .cmp(&b.name.as_deref().unwrap_or("").to_lowercase()) + }); + Ok(Json(out)) +} + +#[derive(Deserialize)] +struct NewTrackedPlaylist { + /// Track this existing Subsonic playlist... + playlist_id: Option, + /// ...or create a new one with this name + name: Option, + #[serde(flatten)] + tracking: Tracking, +} + +#[post("/playlists", data = "")] +async fn create_playlist( + _user: User, + body: Json, + pool: &State, + media_client: &State>, +) -> ApiResult { + body.tracking.validate()?; + + let playlist_id = match (&body.playlist_id, body.name.as_deref().map(str::trim)) { + (Some(id), _) => { + media_client + .get_playlist(id) + .await + .map_err(|_| fail(Status::UnprocessableEntity, "That playlist doesn't exist"))?; + let tracked = sqlx::query_scalar!( + r#"SELECT COUNT(*) AS "count!" FROM "tracked_playlist" WHERE playlist_id = $1"#, + id + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + if tracked > 0 { + return Err(fail( + Status::Conflict, + "That playlist is already being tracked", + )); + } + if mix_playlist_ids(pool.inner()).await?.contains(id) { + return Err(fail( + Status::Conflict, + "That's a genre mix, which playlistd already keeps up to date", + )); + } + id.clone() + } + (None, Some(name)) if !name.is_empty() => { + media_client + .create_playlist(name) + .await + .map_err(subsonic_error)? + .id + } + _ => { + return Err(fail( + Status::UnprocessableEntity, + "Choose a playlist or enter a name", + )) + } + }; + + let id = Uuid::new_v4(); + sqlx::query!( + r#" + INSERT INTO "tracked_playlist" (id, playlist_id, playlist_size, tracking_user, tracking_type) + VALUES ($1, $2, $3, $4, $5) + "#, + id, + playlist_id, + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +#[derive(Deserialize)] +struct TrackedPlaylistUpdate { + /// Rename the playlist in Subsonic + name: Option, + #[serde(flatten)] + tracking: Tracking, +} + +#[put("/playlists/", data = "")] +async fn update_tracked_playlist( + _user: User, + id: &str, + body: Json, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + body.tracking.validate()?; + + let row = sqlx::query_as!( + TrackedPlaylist, + r#" + UPDATE "tracked_playlist" SET playlist_size = $1, tracking_user = $2, tracking_type = $3 + WHERE id = $4 + RETURNING * + "#, + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + id, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + if let (Some(name), Some(playlist_id)) = (body.name.as_deref().map(str::trim), &row.playlist_id) + { + if !name.is_empty() { + media_client + .rename_playlist(playlist_id, name) + .await + .map_err(subsonic_error)?; + } + } + + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +/// Stop tracking a playlist, optionally deleting it from Subsonic too +#[delete("/playlists/?")] +async fn delete_tracked_playlist( + _user: User, + id: &str, + delete_playlist: Option, + pool: &State, + media_client: &State>, +) -> Result>> { + let row = sqlx::query_as!( + TrackedPlaylist, + r#"DELETE FROM "tracked_playlist" WHERE id = $1 RETURNING *"#, + parse_id(id)? + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + if delete_playlist.unwrap_or(false) { + if let Some(playlist_id) = row.playlist_id { + // it may already be gone from Subsonic + if let Err(e) = media_client.delete_playlist(&playlist_id).await { + log::warn!("Could not delete playlist {}: {}", playlist_id, e); + } + } + } + Ok(Status::NoContent) +} + +/// Update a tracked playlist's songs now, rather than on the next daemon tick +#[post("/playlists//refresh")] +async fn refresh( + _user: User, + id: &str, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + + let result = update_playlist(media_client.inner().clone(), row) + .await + .map_err(|e| e.to_string()); + if let Err(e) = result { + return Err(fail( + Status::BadGateway, + format!("Couldn't update the playlist: {}", e), + )); + } + + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +#[derive(Serialize)] +struct SubsonicPlaylist { + id: String, + name: String, + song_count: usize, + tracked: bool, +} + +/// Playlists maintained as genre mixes, which mustn't also be tracked +async fn mix_playlist_ids(pool: &PgPool) -> Result, Custom>> { + sqlx::query_scalar!(r#"SELECT playlist_id FROM "cluster_mix_playlist""#) + .fetch_all(pool) + .await + .map_err(db_error) +} + +/// Subsonic playlists that could be tracked (genre mixes are left out) +#[get("/subsonic-playlists")] +async fn subsonic_playlists( + _user: User, + pool: &State, + media_client: &State>, +) -> ApiResult> { + let tracked: Vec = TrackedPlaylist::all(pool.inner()) + .await + .map_err(db_error)? + .into_iter() + .filter_map(|p| p.playlist_id) + .collect(); + let mixes = mix_playlist_ids(pool.inner()).await?; + let mut out: Vec = media_client + .get_playlists() + .await + .map_err(subsonic_error)? + .into_iter() + .filter(|p| !mixes.contains(&p.id)) + .map(|p| SubsonicPlaylist { + tracked: tracked.contains(&p.id), + id: p.id, + name: p.name, + song_count: p.song_count, + }) + .collect(); + out.sort_by_key(|p| p.name.to_lowercase()); + Ok(Json(out)) +} + +// --------------------------------------------------------------------------- +// Rules +// --------------------------------------------------------------------------- + +#[derive(Serialize)] +struct RuleView { + #[serde(flatten)] + rule: CreateTrackedPlaylist, + /// The name the rule's next playlist will have, if it differs from the last one + current_name: Option, +} + +fn rule_view(rule: CreateTrackedPlaylist) -> RuleView { + RuleView { + current_name: format_template(&rule.name_template).ok(), + rule, + } +} + +#[get("/rules")] +async fn rules(_user: User, pool: &State) -> ApiResult> { + let mut rules = CreateTrackedPlaylist::all(pool.inner()) + .await + .map_err(db_error)?; + rules.sort_by(|a, b| a.name_template.cmp(&b.name_template)); + Ok(Json(rules.into_iter().map(rule_view).collect())) +} + +#[derive(Deserialize)] +struct RuleBody { + name_template: String, + #[serde(flatten)] + tracking: Tracking, +} + +#[post("/rules", data = "")] +async fn create_rule( + _user: User, + body: Json, + pool: &State, +) -> ApiResult { + body.tracking.validate()?; + format_template(&body.name_template)?; + + let rule = sqlx::query_as!( + CreateTrackedPlaylist, + r#" + INSERT INTO "create_tracked_playlist" (id, name_template, playlist_size, tracking_user, tracking_type) + VALUES ($1, $2, $3, $4, $5) + RETURNING * + "#, + Uuid::new_v4(), + body.name_template.trim(), + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + Ok(Json(rule_view(rule))) +} + +/// Changes apply to playlists the rule creates from now on +#[put("/rules/", data = "")] +async fn update_rule( + _user: User, + id: &str, + body: Json, + pool: &State, +) -> ApiResult { + body.tracking.validate()?; + format_template(&body.name_template)?; + + let rule = sqlx::query_as!( + CreateTrackedPlaylist, + r#" + UPDATE "create_tracked_playlist" + SET name_template = $1, playlist_size = $2, tracking_user = $3, tracking_type = $4 + WHERE id = $5 + RETURNING * + "#, + body.name_template.trim(), + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + parse_id(id)?, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + Ok(Json(rule_view(rule))) +} + +/// Delete a rule. Playlists it already created keep being tracked. +#[delete("/rules/")] +async fn delete_rule( + _user: User, + id: &str, + pool: &State, +) -> Result>> { + let result = sqlx::query!( + r#"DELETE FROM "create_tracked_playlist" WHERE id = $1"#, + parse_id(id)? + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + if result.rows_affected() == 0 { + return Err(fail(Status::NotFound, "Not found")); + } + Ok(Status::NoContent) +} + +#[derive(Serialize)] +struct NamePreview { + name: String, +} + +/// What a name template produces today +#[get("/preview-name?