Commit 78eaff23 authored by Kourser's avatar Kourser
Browse files

feat(downloads): a global automatic download, overridable per podcast

A listener asked to set automatic downloads once for every podcast —
keep the ten latest unplayed episodes — with a few podcasts keeping
fewer.

Settings › Downloads gains "For all podcasts" and "Unplayed episodes to
keep" (3, 5, 10 or unlimited; 3 by default). A podcast's settings offer
"Global setting (…)" besides on and off, and its own number:
PodcastPreferences.autoDownload and keepUnplayed (was
episodeCacheLimit) are nil when the podcast follows the global setting.

The limit now counts unplayed episodes, and is kept rather than applied
to new arrivals only: the store's autoDownloadPlan lists the most recent
unplayed episodes to fetch and the automatic downloads to delete. A
download the user asked for, a queued, favourite or started episode and
the one playing are never deleted; downloads record whether they were
automatic, carried through relaunches in the transfer's description.
"Unlimited" still downloads each new episode and deletes nothing. The
policy applies at each refresh and at once when a setting changes, and
does nothing while the Wi-Fi or charging conditions forbid downloading.

Migration v12: a podcast that auto-downloaded keeps doing so, with its
limit, as its own setting; the others follow the global setting, off by
default, so nothing changes by itself. Their existing downloads are
taken as automatic, as the old cleanup treated them. Restoring a backup
made by an older version now migrates it at once, not at the next
launch.

New strings in the 23 languages.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 671b58ea
Loading
Loading
Loading
Loading
+16
Changes for CHANGELOG.md: 16 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,22 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).

## [Non publié]

### Ajouté
- **Téléchargement automatique pour tous les podcasts** : il s'active dans
  Réglages › Téléchargement, avec le nombre d'épisodes non lus à garder
  téléchargés (3, 5, 10 ou illimité). Chaque podcast suit ce réglage global ou
  a le sien : activé ou désactivé, et son propre nombre d'épisodes.

### Modifié
- Le nombre d'épisodes à conserver compte désormais les épisodes **non lus**.
  Les plus récents sont téléchargés, y compris un épisode plus ancien qui
  rentre dans le compte quand un autre est lu ; les téléchargements
  automatiques plus anciens ou déjà lus sont supprimés au rafraîchissement.
  Un épisode téléchargé à la main, dans la file d'attente, dans « À écouter
  plus tard » ou commencé n'est jamais supprimé.
- Un podcast qui avait le téléchargement automatique le garde, avec sa limite ;
  les autres suivent le réglage global, désactivé par défaut.

## [1.5.0] - 2026-10-31

Première version Mac depuis la 1.3.0 : elle reprend aussi ce qui le concerne
+2 −1
Changes for Packages/Core/Package.swift: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -58,7 +58,8 @@ let package = Package(
        ),
        .testTarget(
            name: "StorageKitTests",
            dependencies: ["StorageKit", "PodcastModel"]
            // GRDB itself, to build the older schemas the migration tests start from.
            dependencies: ["StorageKit", "PodcastModel", .product(name: "GRDB", package: "GRDB.swift")]
        ),
        .testTarget(
            name: "PlaybackKitTests",
+35 −9
Changes for Packages/Core/Sources/PodcastModel/PodcastPreferences.swift: 35 added lines, 9 removed lines.
Original line number Diff line number Diff line
import Foundation

/// Per-subscription playback preferences. A `nil` rate / zero skip means
/// "use the app defaults", so an all-default value is treated as "unset".
/// Per-subscription playback preferences. A `nil` rate or download setting /
/// zero skip means "use the app defaults", so an all-default value is treated
/// as "unset".
public struct PodcastPreferences: Hashable, Sendable, Codable {
    /// Dedicated playback rate for this podcast, or `nil` to use the global rate.
    public var playbackRate: Float?
@@ -9,10 +10,12 @@ public struct PodcastPreferences: Hashable, Sendable, Codable {
    public var skipIntro: Int
    /// Seconds to cut from the end of each episode (auto-advances early).
    public var skipEnd: Int
    /// Whether newly published episodes are downloaded automatically on refresh.
    public var autoDownload: Bool
    /// Most-recent downloaded episodes to keep for this podcast; `0` = unlimited.
    public var episodeCacheLimit: Int
    /// Whether this podcast downloads episodes automatically, or `nil` to
    /// follow the global setting.
    public var autoDownload: Bool?
    /// Most recent unplayed episodes this podcast keeps downloaded (`0` = no
    /// limit), or `nil` to follow the global setting.
    public var keepUnplayed: Int?
    /// Whether to skip silences during playback (downloaded episodes only).
    public var skipSilence: Bool
    /// Volume factor (0...1) multiplied into the app volume; `1` = unchanged.
@@ -26,8 +29,8 @@ public struct PodcastPreferences: Hashable, Sendable, Codable {
        playbackRate: Float? = nil,
        skipIntro: Int = 0,
        skipEnd: Int = 0,
        autoDownload: Bool = false,
        episodeCacheLimit: Int = 0,
        autoDownload: Bool? = nil,
        keepUnplayed: Int? = nil,
        skipSilence: Bool = false,
        volume: Float = 1,
        notifyNewEpisodes: Bool = true
@@ -36,7 +39,7 @@ public struct PodcastPreferences: Hashable, Sendable, Codable {
        self.skipIntro = skipIntro
        self.skipEnd = skipEnd
        self.autoDownload = autoDownload
        self.episodeCacheLimit = episodeCacheLimit
        self.keepUnplayed = keepUnplayed
        self.skipSilence = skipSilence
        self.volume = volume
        self.notifyNewEpisodes = notifyNewEpisodes
@@ -44,4 +47,27 @@ public struct PodcastPreferences: Hashable, Sendable, Codable {

    /// All-default preferences, i.e. "no per-podcast overrides".
    public static let none = PodcastPreferences()

    /// The automatic download policy in force for this podcast: its own
    /// settings where it has some, the global ones otherwise.
    public func autoDownloadPolicy(global: AutoDownloadPolicy) -> AutoDownloadPolicy {
        AutoDownloadPolicy(
            isEnabled: autoDownload ?? global.isEnabled,
            keepUnplayed: keepUnplayed ?? global.keepUnplayed
        )
    }
}

/// Which episodes a subscription keeps downloaded without being asked.
public struct AutoDownloadPolicy: Hashable, Sendable {
    public var isEnabled: Bool
    /// The most recent unplayed episodes kept downloaded: missing ones are
    /// fetched, automatic downloads outside them deleted. `0` = no limit: each
    /// new episode is downloaded as it comes, and nothing is deleted.
    public var keepUnplayed: Int

    public init(isEnabled: Bool, keepUnplayed: Int) {
        self.isEnabled = isEnabled
        self.keepUnplayed = keepUnplayed
    }
}
+3
Changes for Packages/Core/Sources/StorageKit/LibraryStore+Backup.swift: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -18,5 +18,8 @@ extension LibraryStore {
    public func restoreDatabase(from url: URL) async throws {
        let source = try DatabaseQueue(path: url.path)
        try source.backup(to: dbQueue)
        // A backup made by an older version brings its older schema along:
        // bring it up to date now, not at the next launch.
        try Self.migrator.migrate(dbQueue)
    }
}
+55 −2
Changes for Packages/Core/Sources/StorageKit/LibraryStore+QueueDownload.swift: 55 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -105,10 +105,12 @@ private extension Array {

extension LibraryStore {
    /// Records a completed download (the file name within the downloads folder).
    public func markDownloaded(episodeID id: UUID, fileName: String) async throws {
    /// `isAutomatic` marks one the automatic download policy made, and may
    /// therefore delete again.
    public func markDownloaded(episodeID id: UUID, fileName: String, isAutomatic: Bool = false) async throws {
        let episodeId = id.uuidString
        try await dbQueue.write { db in
            try DownloadRecord(episodeId: episodeId, fileName: fileName).upsert(db)
            try DownloadRecord(episodeId: episodeId, fileName: fileName, isAutomatic: isAutomatic).upsert(db)
        }
    }

@@ -162,3 +164,54 @@ extension LibraryStore {
        }
    }
}

// MARK: - Automatic downloads

/// What keeps a subscription at its automatic download policy.
public struct AutoDownloadPlan: Equatable, Sendable {
    /// Episodes to download, newest first.
    public var toDownload: [Episode]
    /// Automatic downloads to delete.
    public var toDelete: [Episode]
}

extension LibraryStore {
    /// The downloads that leave a subscription with its `keepUnplayed` most
    /// recent unplayed episodes, and no other automatic download.
    ///
    /// Never deleted: a download the user asked for, an episode in the queue,
    /// in "à écouter plus tard" or started, and those in `protecting` (the one
    /// playing). `toDownload` lists what has no completed download yet — a
    /// transfer may already be under way.
    public func autoDownloadPlan(
        forPodcastID id: UUID, keepUnplayed: Int, protecting: Set<UUID> = []
    ) async throws -> AutoDownloadPlan {
        let podcastId = id.uuidString
        return try await dbQueue.read { db in
            let episodes = try EpisodeRecord
                .filter(Column("podcastId") == podcastId && Column("enclosureURL") != nil)
                .order(Column("publicationDate").desc)
                .fetchAll(db)
            let keys = episodes.map(\.id)
            let states = try PlayStateRecord.filter(keys: keys).fetchAll(db)
            let played = Set(states.filter(\.isPlayed).map(\.episodeId))
            let started = Set(states.filter { !$0.isPlayed && $0.position > 0 }.map(\.episodeId))
            let downloads = try DownloadRecord.filter(keys: keys).fetchAll(db)
            let downloaded = Set(downloads.map(\.episodeId))
            let automatic = Set(downloads.filter(\.isAutomatic).map(\.episodeId))
            let queued = Set(try QueueRecord.filter(keys: keys).fetchAll(db).map(\.episodeId))
            let favorites = Set(try FavoriteRecord.filter(keys: keys).fetchAll(db).map(\.episodeId))
            let kept = Set(protecting.map(\.uuidString))
                .union(queued).union(favorites).union(started)

            let wanted = episodes.filter { !played.contains($0.id) }.prefix(keepUnplayed)
            let wantedIDs = Set(wanted.map(\.id))
            return AutoDownloadPlan(
                toDownload: wanted.filter { !downloaded.contains($0.id) }.map { $0.toModel() },
                toDelete: episodes
                    .filter { automatic.contains($0.id) && !wantedIDs.contains($0.id) && !kept.contains($0.id) }
                    .map { $0.toModel() }
            )
        }
    }
}
Loading