Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,33 @@ Connects Silo profiles to a self-hosted [Floppy](https://github.com/dannyvfilms/
- Imports durable movie and episode resume progress.
- Exports completed movie and episode watches.
- Sends live playback start, pause, and stop events.
- Imports and exports movie and series ratings.
- Uses provider timestamps and Floppy history lookups to make completed-watch retries idempotent.

The plugin deliberately does not advertise favorites, watchlists, or unwatched export. Floppy does not currently expose those concepts with the stable identifiers and semantics required by Silo's reconciliation contract. Silo only enables capabilities a plugin explicitly advertises.
The plugin deliberately does not advertise favorites, watchlists, or unwatched export. Floppy does not currently expose those concepts with the stable identifiers and semantics required by Silo's reconciliation contract. Silo only enables capabilities a plugin explicitly advertises, so listing the series media type for ratings does not turn on series favorites or watchlist sync.

## Ratings

This version needs a Silo server release that supports rating sync for watch-provider plugins. An older server handles it in one of two ways:

- A server that parses the manifest built into the plugin binary rejects the update.
- A server that installs from the release archive and discards manifest fields it does not know ignores the rating flags and the series media type. The plugin then syncs history, progress, and scrobbles without ratings.

Floppy scores titles from 0 to 10 in steps of 0.1, and Silo's plugin contract uses whole ratings from 1 to 10:

- Import rounds a Floppy score half up and clamps it to 1–10, so 7.5 becomes 8 and 0 becomes 1.
- Export writes the rating as the title's score, and a removal clears the score.

Every rating import reads the full set of rated movies, then rated TV shows, as a complete snapshot. Floppy has no feed of rating changes, so there is no incremental import, and Silo treats a title missing from the snapshot as unrated. Each page re-reads the last title of the page before it. If a rating added or cleared during the read has shifted the list, or the plugin cannot read a listed title's rating, the plugin abandons the snapshot instead of leaving titles out, and the next sync starts over.

Floppy stores a rating on the title it tracks, so:

- Only TMDB titles sync. Floppy tracks movies and TV from TMDB or manual entries, and the plugin cannot address manual entries or TV that Floppy keeps in its anime library.
- Silo can rate a title only after Floppy tracks it. A rating for an untracked title is rejected as "Floppy is not tracking this title", and removing a rating from an untracked title succeeds without a change.
- Floppy can hold several entries for one title, one per viewing, and shows the score on the most recently active entry that has one. Floppy's rated list reports the newest entry's score instead, so import reads each rated title's entries to find the score Floppy shows, one extra request per title. Export puts the rating on the newest entry, and also on a more recently active entry that shows a different score. A removal clears the score on every entry.
- For a movie watched through Floppy's play API, Floppy lists per-play records instead of entries, and the plugin can reach only the newest entry. It writes the rating there, and a snapshot fails if the score Floppy shows sits on an older entry.

A scoped Floppy token needs `watchlist:read` to import ratings and `watchlist:write` to send them. Floppy's tracking preset includes both, and legacy full-access tokens need no change. Without `watchlist:write`, each rating update fails with a message that the token needs that scope, and history, progress, and scrobble sync continue.

## Setup

Expand All @@ -24,12 +48,16 @@ The plugin requires a Floppy release that provides:

- `GET /apis/listenbrainz/1/validate-token`
- `GET /api/v1/history/`
- `GET /api/v1/media/{media_type}/` with the `rating=rated` filter
- `PATCH /api/v1/media/{media_type}/{source}/{media_id}/`
- `GET /api/v1/media/{media_type}/{source}/{media_id}/history/`
- `PATCH /api/v1/media/{media_type}/{source}/{media_id}/history/{consumption_id}/`
- `GET /api/v1/playback/progress/`
- `POST /api/v1/scrobble/`

## Development

The plugin currently pins `silo-plugin-sdk` v0.13.2 in `go.mod`.
The plugin builds against the `silo-plugin-sdk` rating contract (v0.17.0 once tagged).

```bash
make test
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/Silo-Server/silo-plugin-watchprovider-floppy
go 1.26.5

require (
github.com/Silo-Server/silo-plugin-sdk v0.13.2
github.com/Silo-Server/silo-plugin-sdk v0.16.2-0.20260923231249-95b81a099ca7
google.golang.org/protobuf v1.36.11
)

Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
github.com/Silo-Server/silo-plugin-sdk v0.13.2 h1:w7U0mmljVPauKfzRLNKusuiYFpuoEhuCSX4Hp3s9eRw=
github.com/Silo-Server/silo-plugin-sdk v0.13.2/go.mod h1:etqmxLTwjxpFH9goAjBDfNDoqHMv2/sqUXu8yx3hNfA=
github.com/Silo-Server/silo-plugin-sdk v0.16.2-0.20260923231249-95b81a099ca7 h1:7aVKMCncxENZ5QNXbDa99q/M12Y1KZSp/h/eQlFS3yU=
github.com/Silo-Server/silo-plugin-sdk v0.16.2-0.20260923231249-95b81a099ca7/go.mod h1:abwsCEKuPAAgeAqpNGbwoaut2eQlC/Kj97u89Vvg9qM=
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
Expand Down
24 changes: 24 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"testing"

pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1"
"github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest"
)

Expand All @@ -24,3 +25,26 @@ func TestManifestDeclaresPerConnectionFloppyServer(t *testing.T) {
t.Fatalf("global config schemas = %#v, want none", parsed.GetGlobalConfigSchema())
}
}

func TestManifestAdvertisesMovieAndSeriesRatings(t *testing.T) {
t.Parallel()
parsed, err := manifest.Load(manifestJSON)
if err != nil {
t.Fatalf("load manifest: %v", err)
}
descriptor := parsed.GetCapabilities()[0].GetWatchSyncProvider()
if !descriptor.GetImportRatings() || !descriptor.GetExportRatings() {
t.Fatalf("ratings = import %t export %t, want both", descriptor.GetImportRatings(), descriptor.GetExportRatings())
}
if descriptor.GetImportFavorites() || descriptor.GetExportFavorites() || descriptor.GetImportWatchlist() || descriptor.GetExportWatchlist() {
t.Fatalf("descriptor advertises favorites or watchlist: %v", descriptor)
}
media := map[pluginv1.WatchSyncMediaType]bool{}
for _, mediaType := range descriptor.GetSupportedMediaTypes() {
media[mediaType] = true
}
if !media[pluginv1.WatchSyncMediaType_WATCH_SYNC_MEDIA_TYPE_MOVIE] || !media[pluginv1.WatchSyncMediaType_WATCH_SYNC_MEDIA_TYPE_SERIES] ||
!media[pluginv1.WatchSyncMediaType_WATCH_SYNC_MEDIA_TYPE_EPISODE] {
t.Fatalf("supported media types = %v", descriptor.GetSupportedMediaTypes())
}
}
11 changes: 7 additions & 4 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"type": "watch_sync_provider.v1",
"id": "floppy",
"display_name": "Floppy",
"description": "Bidirectional watch history, resume progress, and live scrobbling for a self-hosted Floppy instance.",
"description": "Bidirectional watch history, movie and series ratings, resume progress, and live scrobbling for a self-hosted Floppy instance.",
"config_schema": [
{
"key": "floppy",
Expand All @@ -40,9 +40,12 @@
"export_watched": true,
"import_watched": true,
"import_progress": true,
"import_ratings": true,
"export_ratings": true,
"supported_media_types": [
"WATCH_SYNC_MEDIA_TYPE_MOVIE",
"WATCH_SYNC_MEDIA_TYPE_EPISODE"
"WATCH_SYNC_MEDIA_TYPE_EPISODE",
"WATCH_SYNC_MEDIA_TYPE_SERIES"
],
"external_id_namespaces": ["tmdb", "imdb", "tvdb"],
"max_batch_size": 50,
Expand All @@ -54,8 +57,8 @@
"presentation": {
"display_name": "Floppy Watch Provider",
"summary": "Sync Silo watch activity with a self-hosted Floppy instance.",
"description_markdown": "Imports movie and episode history and resume progress, exports completed watches, and forwards live playback start, pause, and stop events.",
"setup_markdown": "Connect a Silo profile by entering that profile's Floppy server URL and API token. Different profiles can use different Floppy servers.",
"description_markdown": "Imports movie and episode history and resume progress, exports completed watches, syncs movie and series ratings in both directions, and forwards live playback start, pause, and stop events.",
"setup_markdown": "Connect a Silo profile by entering that profile's Floppy server URL and API token. Different profiles can use different Floppy servers. A scoped Floppy token needs the tracking preset; sending ratings to Floppy uses its `watchlist:write` scope.",
"homepage_url": "https://github.com/dannyvfilms/Floppy",
"source_url": "https://github.com/Silo-Server/silo-plugin-watchprovider-floppy",
"support_url": "https://github.com/Silo-Server/silo-plugin-watchprovider-floppy/issues",
Expand Down
25 changes: 18 additions & 7 deletions provider/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,14 @@ const (
defaultRequestTimeout = 110 * time.Second
)

// apiClient serves one RPC; it is not shared across calls.
type apiClient struct {
baseURL *url.URL
token string
http *http.Client
// tokenValid records that validate-token accepted the token during this
// call, so a 403 from a Bearer route means a missing scope.
tokenValid bool
}

func newAPIClient(rawBaseURL, token string, httpClient *http.Client) (*apiClient, error) {
Expand All @@ -54,17 +58,24 @@ func (c *apiClient) endpoint(path string, query url.Values) string {
}

func (c *apiClient) do(ctx context.Context, method, path string, query url.Values, payload, output any, tokenScheme string) *pluginv1.WatchSyncFault {
_, fault := c.request(ctx, method, path, query, payload, output, tokenScheme)
return fault
}

// request is do plus the HTTP status, which is zero when no response arrived.
// Callers use it when one status needs handling beyond the shared fault.
func (c *apiClient) request(ctx context.Context, method, path string, query url.Values, payload, output any, tokenScheme string) (int, *pluginv1.WatchSyncFault) {
var body io.Reader
if payload != nil {
encoded, err := json.Marshal(payload)
if err != nil {
return permanentFault("Floppy request could not be encoded")
return 0, permanentFault("Floppy request could not be encoded")
}
body = bytes.NewReader(encoded)
}
req, err := http.NewRequestWithContext(ctx, method, c.endpoint(path, query), body)
if err != nil {
return permanentFault("Floppy request could not be created")
return 0, permanentFault("Floppy request could not be created")
}
if payload != nil {
req.Header.Set("Content-Type", "application/json")
Expand All @@ -74,22 +85,22 @@ func (c *apiClient) do(ctx context.Context, method, path string, query url.Value
}
resp, err := c.http.Do(req)
if err != nil {
return temporaryFault("Floppy is temporarily unreachable", 0)
return 0, temporaryFault("Floppy is temporarily unreachable", 0)
}
defer resp.Body.Close()

if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return faultForHTTPResponse(resp)
return resp.StatusCode, faultForHTTPResponse(resp)
}
if output == nil || resp.StatusCode == http.StatusNoContent {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBytes))
return nil
return resp.StatusCode, nil
}
decoder := json.NewDecoder(io.LimitReader(resp.Body, maxResponseBytes))
if err := decoder.Decode(output); err != nil {
return temporaryFault("Floppy returned an unreadable response", 0)
return resp.StatusCode, temporaryFault("Floppy returned an unreadable response", 0)
}
return nil
return resp.StatusCode, nil
}

func faultForHTTPResponse(resp *http.Response) *pluginv1.WatchSyncFault {
Expand Down
4 changes: 2 additions & 2 deletions provider/list_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (s *Server) listWatched(ctx context.Context, client *apiClient, req *plugin
return &pluginv1.WatchSyncListRemoteStateResponse{Fault: temporaryFault("Floppy returned history pages without a usable timestamp", 0)}, nil
}
token.Offset = nextOffset
response.NextPageToken = nextPageToken(token)
response.NextPageToken = encodePageToken(token)
} else if nextCursor := providerNextCursor(cursor, token.HighWater); nextCursor != "" {
response.NextCursor = nextCursor
}
Expand Down Expand Up @@ -137,7 +137,7 @@ func (s *Server) listProgress(ctx context.Context, client *apiClient, req *plugi
last := page[len(page)-1]
token.BoundaryAt = last.updatedAt
token.BoundaryKey = last.key
response.NextPageToken = nextPageToken(token)
response.NextPageToken = encodePageToken(token)
} else if nextCursor := providerNextCursor(cursor, token.HighWater); nextCursor != "" {
response.NextCursor = nextCursor
}
Expand Down
53 changes: 53 additions & 0 deletions provider/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,59 @@ type progressEntry struct {
UpdatedAt string `json:"updated_at"`
}

// ratedMediaResponse is one page of GET /api/v1/media/{media_type}/. Each
// result is one title: Floppy folds repeat consumptions into the newest row,
// and score is that row's own score, which a rewatch leaves empty.
type ratedMediaResponse struct {
Pagination pagination `json:"pagination"`
Results []ratedMediaEntry `json:"results"`
}

type ratedMediaEntry struct {
// ID is Floppy's item ID for the title.
ID json.RawMessage `json:"id"`
Score *float64 `json:"score"`
Item *ratedMediaItem `json:"item"`
}

type ratedMediaItem struct {
MediaType string `json:"media_type"`
MediaID json.RawMessage `json:"media_id"`
Source string `json:"source"`
LibraryMediaType string `json:"library_media_type"`
Title string `json:"title"`
ReleaseDatetime string `json:"release_datetime"`
IDs map[string]any `json:"ids"`
ProviderExternalIDs map[string]any `json:"provider_external_ids"`
}

// consumptionHistoryResponse is one page of GET
// /api/v1/media/{media_type}/{source}/{media_id}/history/.
type consumptionHistoryResponse struct {
Pagination pagination `json:"pagination"`
Results []consumptionHistory `json:"results"`
}

// consumptionHistory is one of a title's consumptions (tracker rows), each
// with its own score. Once a Floppy movie has per-play rows, the route lists
// those plays instead; only they carry the external_id key, and they have no
// score. PATCH .../history/{consumption_id}/ answers with the same shape.
type consumptionHistory struct {
ID int64 `json:"consumption_id"`
Score *float64 `json:"score"`
Status *int `json:"status"`
Created string `json:"created"`
ProgressedAt string `json:"progressed_at"`
EndDate string `json:"end_date"`
ExternalID json.RawMessage `json:"external_id"`
}

// ratingPayload is the PATCH body for a score. A nil Score encodes as JSON
// null, which clears the rating.
type ratingPayload struct {
Score *int32 `json:"score"`
}

type scrobblePayload struct {
Action string `json:"action"`
MediaType string `json:"media_type"`
Expand Down
Loading
Loading