Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,12 @@ docker compose up -d --build

The database lives in `./data` and survives rebuilds. Containers restart on crash and on boot (`restart: unless-stopped`); make sure Docker itself starts at boot with `sudo systemctl enable docker`.

If you are upgrading from a build before persisted series totals, backfill the episode totals used by library cards once:

```bash
docker compose exec web bin/rails series:backfill_totals
```

## Configuration

| Variable | Purpose | Default |
Expand Down
30 changes: 30 additions & 0 deletions app/assets/tailwind/application.css
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,17 @@
white-space: nowrap;
}

.poster-card__progress {
margin-top: 0.125rem;
font-size: 0.6875rem;
letter-spacing: 0.01em;
color: var(--color-ink-400);
font-variant-numeric: tabular-nums;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

@media (hover: hover) {
.poster-card:hover .poster-card__art img {
transform: scale(1.045);
Expand Down Expand Up @@ -662,6 +673,7 @@

.card-action svg { width: 0.8125rem; height: 0.8125rem; }
.card-action:hover { background-color: var(--color-iris-600); color: var(--color-on-accent); }
.card-action--active { background-color: var(--color-iris-600); color: var(--color-on-accent); }
.card-action--danger:hover { background-color: var(--color-rust-500); color: var(--color-ink-50); }

.card-progress {
Expand Down Expand Up @@ -1442,6 +1454,7 @@ details[open] > .source-more svg { transform: rotate(180deg); }
.season-tab {
display: inline-flex;
align-items: center;
gap: 0.3125rem;
height: 2rem;
padding: 0 0.8125rem;
border-radius: 999px;
Expand All @@ -1461,6 +1474,23 @@ details[open] > .source-more svg { transform: rotate(180deg); }
color: var(--color-ink-950);
}

.season-tab__status {
display: inline-flex;
align-items: center;
color: var(--color-sage-400);
}

.season-tab--active .season-tab__status { color: var(--color-sage-950); }

.season-tab__progress {
color: var(--color-ink-400);
font-size: 0.6875rem;
font-variant-numeric: tabular-nums;
letter-spacing: -0.01em;
}

.season-tab--active .season-tab__progress { color: var(--color-ink-800); }

.episode {
border-bottom: 1px solid oklch(1 0 0 / 0.06);
}
Expand Down
34 changes: 30 additions & 4 deletions app/controllers/content_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,30 @@ def show
if @type == "show"
progress_rows = current_user.playback_progresses.for_show(@imdb_id)
@episode_progress = progress_rows.index_by { |progress| [ progress.season_number, progress.episode_number ] }
@episode_finished = @episode_progress.transform_values do |progress|
PlaybackCompletionPolicy.episode_finished?(progress)
end
@selected_season = params[:season]&.to_i || 1
@progress = progress_rows.recently_watched.first&.progress_percentage
# One resolver decides what "continue" means (the in-progress episode,
# else the next one), so the hero button can never disagree with the
# player about which episode it starts.
@resume_target = resume_target if @episode_progress.present?
series_progress = Playback::SeriesProgress.new(@metadata&.dig(:episodes), finished: @episode_finished)
@season_progress = series_progress.seasons
selected_season = @season_progress[@selected_season]
@season_watched = selected_season && selected_season[:watched] == selected_season[:total]
@series_watched = series_progress.complete?
@series_watched_episodes = series_progress.watched_episodes
@series_total_episodes = series_progress.total_episodes
@series_progress_percentage = series_progress.percentage
# A successful response with no episodes says nothing about the series
# total, so it must not overwrite what is already stored.
episodes_known = meta_result.success? && @metadata&.dig(:episodes).present?
persist_series_total(@collection_entry, @series_total_episodes) if episodes_known
else
# Movie progress
@progress = current_user.playback_progresses.movies_only
.find_by(imdb_id: @imdb_id)
&.progress_percentage
@movie_progress = current_user.playback_progresses.movies_only.find_by(imdb_id: @imdb_id)
@movie_watched = @movie_progress.present? && PlaybackCompletionPolicy.movie_finished?(@movie_progress)
end
end

Expand Down Expand Up @@ -103,6 +116,19 @@ def episode_streams

private

# Library cards read this stored total instead of calling the catalogue on
# every page load. The series page is the authoritative place to refresh it.
def persist_series_total(entry, total)
return if entry.blank? || entry.series_total_episodes == total

entry.update_columns(
Comment thread
vitobotta marked this conversation as resolved.
Resolved
series_total_episodes: total,
series_total_episodes_synced_at: Time.current
)
rescue ActiveRecord::ActiveRecordError => e
Rails.logger.warn("[ContentController] series total sync failed: #{e.class}: #{e.message}")
end

# What the hero "Continue" button should start: the in-progress episode, or
# the next one when the last episode was finished. PlaybackResumeService owns
# that decision and already degrades to a failure rather than raising.
Expand Down
31 changes: 31 additions & 0 deletions app/controllers/library_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,36 @@ def index
@progress_map = progress_rows.group_by(&:imdb_id).transform_values do |rows|
rows.map(&:progress_percentage).max.to_i
end
@movie_watched_map = progress_rows.select(&:movie?).group_by(&:imdb_id).transform_values do |rows|
rows.any?(&:watched?)
end
@series_progress_map = series_progress_map(@entries, progress_rows)
end

private

# Series cards use the total persisted when the series page loaded and the
# user's local progress rows, so loading the library never calls the
# catalogue.
def series_progress_map(entries, progress_rows)
rows_by_show = progress_rows.select(&:episode?).group_by(&:imdb_id)

entries.select(&:show?).each_with_object({}) do |entry, result|
total = entry.series_total_episodes.to_i
next unless total.positive?

watched = Array(rows_by_show[entry.imdb_id]).count do |row|
row.season_number.positive? && row.watched?
end
next unless watched.positive?

watched = [ watched, total ].min
result[entry.imdb_id] = {
watched: watched,
total: total,
percentage: ((watched.to_f / total) * 100).round,
complete: watched == total
}
end
end
end
44 changes: 44 additions & 0 deletions app/controllers/watched_items_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

class WatchedItemsController < ApplicationController
include ContentParamValidation

before_action :authenticate_user!

def update
imdb_id = params[:imdb_id]
type = params[:type]

return if reject_invalid_imdb_id!(imdb_id) || reject_invalid_content_type!(type)

unless parental_content_policy.allowed?(imdb_id)
redirect_back fallback_location: root_path, alert: "This content is not available for this account."
return
end

if params[:watched].nil?
redirect_back fallback_location: content_path(type: type, imdb_id: imdb_id), alert: "Watched state is required."
return
end
watched = ActiveModel::Type::Boolean.new.cast(params[:watched])

result = Playback::WatchedToggle.new(current_user).call(
imdb_id: imdb_id,
type: type,
season: params[:season],
episode: params[:episode],
watched: watched,
title: params[:title],
poster_url: params[:poster_url],
duration_seconds: params[:duration_seconds]
)

if result.failure?
redirect_back fallback_location: content_path(type: type, imdb_id: imdb_id), alert: result.error_message
return
end

redirect_back fallback_location: content_path(type: type, imdb_id: imdb_id),
notice: watched ? "Marked as watched." : "Marked as unwatched."
end
end
1 change: 1 addition & 0 deletions app/models/collection_entry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class CollectionEntry < ApplicationRecord

validates :imdb_id, :title, presence: true
validates :imdb_id, uniqueness: { scope: :user_id, message: "already in your collection" }
validates :series_total_episodes, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
validates :year, numericality: { greater_than: 1800, less_than: 2100 }, allow_nil: true

scope :by_type, ->(type) { where(content_type: type) }
Expand Down
7 changes: 7 additions & 0 deletions app/models/playback_progress.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,15 @@ class PlaybackProgress < ApplicationRecord
scope :episodes_only, -> { where(content_type: :episode) }

def progress_percentage
# A manual "mark watched" is authoritative even when the catalogue has no
# runtime for the title, so it always displays as complete.
return 100 if completed?
return progress_seconds.positive? ? 1 : 0 unless duration_seconds.positive?

((progress_seconds.to_f / duration_seconds) * 100).round.clamp(0, 100)
end

def watched?
episode? ? PlaybackCompletionPolicy.episode_finished?(self) : PlaybackCompletionPolicy.movie_finished?(self)
end
end
3 changes: 2 additions & 1 deletion app/services/playback/continue_watching_query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def resolve_batch(batch)

def unfinished_movies
@user.playback_progresses.movies_only
.where(completed: false)
.where("duration_seconds <= 0 OR progress_seconds * 100 < duration_seconds * ?", PlaybackCompletionPolicy::MOVIE_PERCENTAGE)
.recently_watched.limit(LIMIT).to_a
end
Expand Down Expand Up @@ -70,7 +71,7 @@ def item(entry)

if entry.episode? && PlaybackCompletionPolicy.episode_finished?(entry)
following = @episode_sequence.next_episode_after(content_ref)
return if following.error_code == :series_complete
return if [ :series_complete, :not_released ].include?(following.error_code)
if following.success?
content_ref = following.data.content_ref
progress = 0
Expand Down
6 changes: 5 additions & 1 deletion app/services/playback/progress_writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ def call(content_ref:, progress_seconds:, duration_seconds:, title: nil, poster_
poster_url: poster_url.presence || stored_poster(content_ref),
watched_at: Time.current,
progress_seconds: progress,
duration_seconds: duration
duration_seconds: duration,
# Real playback supersedes a manual "mark watched" flag. Completion is
# still derived from the saved percentage, so finishing the file keeps
# the title watched without leaving a stale manual flag behind.
completed: false
)
entry.save!
RefreshRecommendationsJob.enqueue_debounced(@user.id) if is_new
Expand Down
62 changes: 62 additions & 0 deletions app/services/playback/series_progress.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# frozen_string_literal: true

module Playback
# Counts watched progress across a series using only episodes that have
# already aired. Specials (season 0) and unreleased episodes are excluded,
# matching the series and season watched actions.
class SeriesProgress
def initialize(episodes, finished:)
@episodes = Array(episodes).select { |episode| released?(episode) }
@finished = finished
end

def seasons
@seasons ||= @episodes.group_by { |episode| episode[:season].to_i }.transform_values do |episodes|
watched = episodes.count { |episode| @finished[key(episode)] }
{ watched: watched, total: episodes.size }
end
end

def watched_episodes
seasons.values.sum { |season| season[:watched] }
end

def total_episodes
seasons.values.sum { |season| season[:total] }
end

def percentage
return 0 unless total_episodes.positive?

((watched_episodes.to_f / total_episodes) * 100).round
end

def complete?
total_episodes.positive? && watched_episodes == total_episodes
end

def summary
{
watched: watched_episodes,
total: total_episodes,
percentage: percentage,
complete: complete?
}
end

private

def key(episode)
[ episode[:season].to_i, episode[:episode].to_i ]
end

def released?(episode)
return false unless episode[:season].to_i.positive?
return false if episode[:released].blank?

Date.parse(episode[:released].to_s) <= Date.current
rescue ArgumentError
false
end
end
end
51 changes: 51 additions & 0 deletions app/services/playback/series_total_backfill.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# frozen_string_literal: true

module Playback
# Fills persisted released-episode totals for library shows that predate the
# collection-entry totals. Failures leave the entry untouched so a later run
# can retry it.
class SeriesTotalBackfill
Result = Struct.new(:updated, :skipped, :failed, :failed_ids, keyword_init: true)

def initialize(catalog: Catalog::CinemetaClient.new, logger: Rails.logger)
@catalog = catalog
@logger = logger
end

def call(entries)
result = Result.new(updated: 0, skipped: 0, failed: 0, failed_ids: [])

entries.find_each do |entry|
if entry.show?
sync(entry, result)
else
result.skipped += 1
end
end

result
end

private

def sync(entry, result)
metadata = @catalog.metadata(entry.imdb_id, "show", include_ratings: false)
unless metadata.success?
result.failed += 1
result.failed_ids << entry.imdb_id
return
end

total = SeriesProgress.new(metadata.data[:episodes], finished: {}).total_episodes
entry.update_columns(
series_total_episodes: total,
series_total_episodes_synced_at: Time.current
)
result.updated += 1
rescue StandardError => e
@logger.warn("[Playback::SeriesTotalBackfill] #{entry.imdb_id}: #{e.class}: #{e.message}")
result.failed += 1
result.failed_ids << entry.imdb_id
end
end
end
Loading
Loading