mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-23 02:20:01 +01:00
* feat(jellyfin): advertise Jellyfin server version 12.1.0
Streamyfin, jellyfin-android and jellyfin-androidtv refuse servers older than
10.10, Swiftfin warns below 12.0, and @jellyfin/sdk flags anything below its
minimum as unsupported, so 10.9.11 locked those clients out. 12.1.0 is the
current Jellyfin release (after 10.11 Jellyfin renumbered to 12.0). No client
checked has an upper bound or assumes the major is 10, and the value keeps
three parts because the Kotlin SDK and Swiftfin reject two-part versions.
* feat(jellyfin): acknowledge POST /Sessions/Playing/Ping
Jellyfin clients ping this endpoint to keep a transcode job alive while
paused. Navidrome ties transcodes to the stream request, so there is nothing
to keep alive; answer 204 like Jellyfin instead of a 404. It shares one no-op
handler with Sessions/Capabilities, renamed to acknowledge.
* feat(jellyfin): reorder playlist entries via Items/{entryId}/Move
Adds POST /Playlists/{id}/Items/{entryId}/Move/{newIndex}, which clients use
to reorder playlists. It maps the entry's PlaylistItemId (its position) and
Jellyfin's zero-based newIndex onto the existing core ReorderTrack, which
enforces ownership. As in Jellyfin, an index past the end appends and an
unknown entry is a no-op; out-of-range positions never reach Reorder, which
would otherwise shift unrelated rows.
* feat(jellyfin): honor position when adding items to a playlist
POST /Playlists/{id}/Items takes an optional zero-based position (added to
the Jellyfin spec in 12.0). Match Jellyfin: zero or negative prepends, past
the end appends, otherwise the new items are inserted at that index in the
order they were added.
Adds PlaylistTrackRepository.Insert and core playlists.InsertTracks, which
shift the following entries and insert in one transaction, instead of
appending and moving each new track with its own ReorderTrack call.
* feat(jellyfin): add type-specific InstantMix routes
Jellyfin exposes InstantMix under Songs/, Albums/, Artists/ and Playlists/
as well as Items/, plus the legacy Artists/InstantMix and
MusicGenres/InstantMix forms that take the seed as ?id=. Clients generated
from the Jellyfin SDKs call the type-specific routes, which 404ed. All of them
now share the existing Items/{id}/InstantMix handler; the external provider
already builds mixes from song, album, artist, playlist and genre seeds.
* feat(jellyfin): honor Width, Height and Fill* image size params
The image endpoint only read MaxWidth/MaxHeight, so clients that size covers
with fillWidth/fillHeight (Manet, Finamp) or width/height got the full-size
original on a cold artwork cache: a 578 KB PNG instead of a 13 KB resize.
Jellyfin applies Width/Height, caps them with MaxWidth/MaxHeight, then
shrinks to the smallest size that still covers the Fill box. Navidrome
resizes on one dimension, so the tightest bound wins and a fill box counts
as its larger side.
* feat(jellyfin): answer HEAD on audio, file and image routes
Fintunes sends HEAD to /Audio/{id}/universal to read the content type and
detect direct play (a Content-Length means direct play), and to the audio and
image URLs before a download, aborting the download when it fails. Those routes
were GET-only, so HEAD got a 404. HEAD now reuses the GET handlers. Direct
play goes through Stream.Serve, which already answers HEAD; a transcode
answers with the target content type and no length without starting ffmpeg,
so a probe never costs a transcode.
* fix(jellyfin): clamp playlist move and insert positions before adding one
movePlaylistItem computed min(newIndex+1, SongCount): newIndex=MaxInt wrapped
to a negative position, and Reorder then left the playlist with a gap
(positions 2, 3, 999998), making the moved entry unmovable. Clamp against the
playlist length first. addToPlaylist's min(position, MaxInt32)+1 wrapped on
32-bit builds and req.Int truncated large values there, so a far-past-the-end
position prepended; parse as int64 and clamp before converting.
* fix(playlists): validate reorder positions inside the write transaction
Reorder never checked its positions, so a source outside the playlist or a
destination past its end shifted rows around a missing entry and left a gap
(e.g. ids 1 and 3), which made the moved entry unmovable afterwards. The
Jellyfin Move handler guarded this with a SongCount read before ReorderTrack,
but a concurrent removal between the two reopened it, and the native API
reorder endpoint passed client positions through unchecked.
Reorder now reads the last position in the same transaction, returns
ErrNotFound for a source outside the playlist and clamps the destination.
ReorderTrack uses an immediate transaction so that read and the updates are
atomic against other writers. The Jellyfin handler drops its pre-check and
maps ErrNotFound to Jellyfin's no-op 204; the native API now answers 404 for
an unknown track instead of corrupting the order.
203 lines
6.6 KiB
Go
203 lines
6.6 KiB
Go
package jellyfin
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"errors"
|
|
"image"
|
|
_ "image/gif"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/dustin/go-humanize"
|
|
"github.com/navidrome/navidrome/conf"
|
|
"github.com/navidrome/navidrome/core/artwork"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/model/request"
|
|
"github.com/navidrome/navidrome/server/imghttp"
|
|
"github.com/navidrome/navidrome/utils/req"
|
|
_ "golang.org/x/image/webp"
|
|
)
|
|
|
|
// imageSize reduces Jellyfin's size params to Navidrome's single bound. Width/Height/Max* are
|
|
// bounds, so the tightest wins; Fill* must cover its box, so its larger side is the bound.
|
|
func imageSize(p *req.Values) int {
|
|
fill := max(p.IntOr("fillwidth", 0), p.IntOr("fillheight", 0))
|
|
size := 0
|
|
for _, v := range []int{p.IntOr("width", 0), p.IntOr("height", 0), p.IntOr("maxwidth", 0), p.IntOr("maxheight", 0), fill} {
|
|
if v > 0 && (size == 0 || v < size) {
|
|
size = v
|
|
}
|
|
}
|
|
return size
|
|
}
|
|
|
|
func (api *Router) getItemImage(w http.ResponseWriter, r *http.Request) {
|
|
// Public, like Jellyfin's own image routes: clients build cover URLs without credentials, and
|
|
// upstream resolves them with no visibility check either (LibraryManager.ItemIsVisible, null user).
|
|
ctx := request.WithUser(r.Context(), model.User{IsAdmin: true})
|
|
itemId, ok := itemIDParam(w, r, "itemId")
|
|
if !ok {
|
|
return
|
|
}
|
|
size := imageSize(req.Params(r))
|
|
|
|
artID := api.resolveArtworkID(ctx, itemId)
|
|
img, err := api.artwork.GetOrPlaceholder(ctx, artID, size, false)
|
|
switch {
|
|
case errors.Is(err, context.Canceled):
|
|
return
|
|
case err != nil:
|
|
log.Warn(ctx, "Error retrieving artwork", "id", itemId, err)
|
|
http.Error(w, "Not Found", http.StatusNotFound)
|
|
return
|
|
}
|
|
defer img.Close()
|
|
if imghttp.WriteImageHeaders(w, r, img, hashFromTag(r)) {
|
|
return
|
|
}
|
|
// Leave Content-Type unset so net/http sniffs it (covers may be PNG/WebP/JPEG).
|
|
_, _ = io.Copy(w, img)
|
|
}
|
|
|
|
// hashFromTag returns the ?tag query param when it is exactly a 16-char lowercase-hex content
|
|
// hash (what Finamp/Jellyfin clients append), so a matching request can be served immutable.
|
|
func hashFromTag(r *http.Request) string {
|
|
tag := r.URL.Query().Get("tag")
|
|
if len(tag) != 16 {
|
|
return ""
|
|
}
|
|
for _, c := range tag {
|
|
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
|
return ""
|
|
}
|
|
}
|
|
return tag
|
|
}
|
|
|
|
// resolveArtworkID maps a Jellyfin item id to a Navidrome ArtworkID, probing
|
|
// album -> artist -> media file -> playlist.
|
|
func (api *Router) resolveArtworkID(ctx context.Context, itemId string) string {
|
|
if al, err := api.ds.Album(ctx).Get(itemId); err == nil {
|
|
return al.CoverArtID().String()
|
|
}
|
|
if ar, err := api.ds.Artist(ctx).Get(itemId); err == nil {
|
|
return ar.CoverArtID().String()
|
|
}
|
|
if mf, err := api.ds.MediaFile(ctx).Get(itemId); err == nil {
|
|
return mf.CoverArtID().String()
|
|
}
|
|
if pl, err := api.ds.Playlist(ctx).Get(itemId); err == nil {
|
|
return pl.CoverArtID().String()
|
|
}
|
|
return (model.ArtworkID{}).String()
|
|
}
|
|
|
|
// postItemImage handles cover upload. Only playlists are writable here; album/artist covers come
|
|
// from scanning. Past the auth and id gates the body is drained before answering — including on the
|
|
// not-implemented path — because Finamp writes it synchronously and would see a broken pipe.
|
|
func (api *Router) postItemImage(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
id, ok := itemIDParam(w, r, "itemId")
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
// Honor the same artwork-upload gate and size cap as the native endpoint.
|
|
u, _ := request.UserFrom(ctx)
|
|
if !conf.Server.EnableArtworkUpload && !u.IsAdmin {
|
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
// The limit caps the decoded image (native endpoint semantics); Jellyfin clients base64-encode
|
|
// the wire body (4/3 bigger), so the read cap allows for inflation.
|
|
limit := artwork.MaxImageUploadSize()
|
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, limit*4/3+4))
|
|
if err != nil {
|
|
log.Warn(ctx, "Jellyfin API: cover upload rejected: body exceeds MaxImageUploadSize",
|
|
"playlistId", id, "limit", humanize.Bytes(uint64(limit)), err)
|
|
http.Error(w, "file too large", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if _, err := api.playlists.Get(ctx, id); err != nil {
|
|
http.Error(w, "Not Implemented", http.StatusNotImplemented)
|
|
return
|
|
}
|
|
|
|
imgBytes, err := decodeImageBody(body)
|
|
if err != nil {
|
|
log.Warn(ctx, "Jellyfin API: cover upload rejected: body is neither an image nor base64", "playlistId", id, err)
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if int64(len(imgBytes)) > limit {
|
|
log.Warn(ctx, "Jellyfin API: cover upload rejected: image exceeds MaxImageUploadSize",
|
|
"playlistId", id, "size", humanize.Bytes(uint64(len(imgBytes))), "limit", humanize.Bytes(uint64(limit)))
|
|
http.Error(w, "file too large", http.StatusBadRequest)
|
|
return
|
|
}
|
|
// Validate by decoding and derive the extension from the real format — clients lie in Content-Type.
|
|
_, format, err := image.DecodeConfig(bytes.NewReader(imgBytes))
|
|
if err != nil {
|
|
log.Warn(ctx, "Jellyfin API: cover upload rejected: not a valid image", "playlistId", id, err)
|
|
http.Error(w, "invalid image file", http.StatusBadRequest)
|
|
return
|
|
}
|
|
ext := "." + format
|
|
|
|
if err := api.playlists.SetImage(ctx, id, bytes.NewReader(imgBytes), ext); err != nil {
|
|
api.internalError(w, r, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// deleteItemImage removes a playlist's uploaded cover. Only playlists are supported.
|
|
func (api *Router) deleteItemImage(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
id, ok := itemIDParam(w, r, "itemId")
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if _, err := api.playlists.Get(ctx, id); err != nil {
|
|
http.Error(w, "Not Implemented", http.StatusNotImplemented)
|
|
return
|
|
}
|
|
|
|
if err := api.playlists.RemoveImage(ctx, id); err != nil {
|
|
api.internalError(w, r, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// decodeImageBody returns the raw image bytes. Jellyfin base64-encodes the body, but some clients
|
|
// send raw bytes, so input already starting with an image magic number is passed through as-is.
|
|
func decodeImageBody(body []byte) ([]byte, error) {
|
|
if isImageMagic(body) {
|
|
return body, nil
|
|
}
|
|
trimmed := bytes.TrimSpace(body)
|
|
return base64.StdEncoding.DecodeString(string(trimmed))
|
|
}
|
|
|
|
func isImageMagic(b []byte) bool {
|
|
switch {
|
|
case len(b) >= 2 && b[0] == 0xFF && b[1] == 0xD8: // JPEG
|
|
return true
|
|
case bytes.HasPrefix(b, []byte{0x89, 'P', 'N', 'G'}): // PNG
|
|
return true
|
|
case bytes.HasPrefix(b, []byte("GIF8")): // GIF (GIF87a/GIF89a)
|
|
return true
|
|
case len(b) >= 12 && bytes.HasPrefix(b, []byte("RIFF")) && bytes.Equal(b[8:12], []byte("WEBP")): // WebP
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|