Commit adcfeaa1 authored by Kourser's avatar Kourser
Browse files

feat(episodes): per-podcast rules on episode titles

A listener follows a show that also publishes each of its chronicles on
its own, next to the full episode, and wanted them hidden or marked
played as they arrive.

A podcast's settings gain "Episode filters": the title contains, does
not contain, or matches a regular expression (case aside, and accents
too for text); the matching episodes are hidden, or marked played.
"Hide similar episodes…" in an episode's context menu starts one,
offering runs of words its title shares with other episodes — frequency
alone cannot tell the show's name from what marks a series, so the user
picks — and previews the episodes it takes.

Hidden episodes leave the podcast's list (a link at its end shows them),
the inbox, which reads on past them, automatic downloads, the "latest
episode" intent and the Touch Bar; search still finds them. New episodes
a rule marks played are neither downloaded nor counted in the
new-episodes notification, and such a rule can also take the episodes
already there. Rules live in a new episode_rule table (migration v13);
a PodcastModelTests target tests their matching.

Also fixed: the podcast settings sheet loads in a task SwiftUI cancels
and restarts as it presents. The cancelled read gave the defaults, which
OK would then have saved over the podcast's settings; it is now dropped.

New strings in the 23 languages.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 3a4ccb63
Loading
Loading
Loading
Loading
+12
Changes for CHANGELOG.md: 12 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -17,6 +17,13 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).
  épisode, et « Tout marquer comme lu » dans le menu Filtrer. Les deux
  agissent sur les épisodes affichés (filtre et recherche compris) et
  demandent confirmation au-delà d'un épisode.
- **Filtres d'épisodes par podcast**, sur le titre (contient, ne contient
  pas, ou expression régulière) : les épisodes concernés sont **masqués**
  (hors de la liste du podcast, des Nouveautés et du téléchargement
  automatique, un lien en bas de liste les affiche) ou **marqués comme lus**
  dès leur arrivée, sans être annoncés. Ils se règlent dans les réglages du
  podcast, ou depuis un épisode avec « Masquer les épisodes similaires… », qui
  propose des textes tirés de son titre et montre les épisodes concernés.

### Modifié
- Le nombre d'épisodes à conserver compte désormais les épisodes **non lus**.
@@ -28,6 +35,11 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).
- 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.

### Corrigé
- Les réglages d'un podcast pouvaient s'ouvrir avec les valeurs par défaut,
  puis les enregistrer sur OK, si leur lecture était interrompue à
  l'ouverture de la fenêtre.

## [1.5.0] - 2026-10-31

Première version Mac depuis la 1.3.0 : elle reprend aussi ce qui le concerne
+4
Changes for Packages/Core/Package.swift: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -51,6 +51,10 @@ let package = Package(
        // Subscription sync with Nextcloud (GPodder Sync) and gpodder.net.
        .target(name: "SyncKit", dependencies: ["PodcastModel"]),

        .testTarget(
            name: "PodcastModelTests",
            dependencies: ["PodcastModel"]
        ),
        .testTarget(
            name: "FeedKitTests",
            dependencies: ["FeedKit", "PodcastModel"],
+135
Changes for Packages/Core/Sources/PodcastModel/EpisodeRule.swift: 135 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation

/// A subscription's rule on episode titles: the episodes it matches are hidden
/// from the lists, or marked played as they arrive — say, the chronicles a show
/// also publishes on their own next to its full episode.
public struct EpisodeRule: Identifiable, Hashable, Sendable, Codable {
    public enum Match: String, Hashable, Sendable, Codable, CaseIterable {
        /// The title contains the text, case and accents aside.
        case contains
        /// The title does not contain the text, case and accents aside.
        case doesNotContain
        /// The title matches a regular expression, case aside.
        case regex
    }

    public enum Action: String, Hashable, Sendable, Codable, CaseIterable {
        /// Kept out of the podcast's list, the inbox and automatic downloads.
        case hide
        /// Marked played as it arrives.
        case markPlayed
    }

    public var id: UUID
    public var match: Match
    public var pattern: String
    public var action: Action

    public init(id: UUID = UUID(), match: Match = .contains, pattern: String = "", action: Action = .hide) {
        self.id = id
        self.match = match
        self.pattern = pattern
        self.action = action
    }

    /// Whether the rule can be applied: some text, and a valid expression for
    /// `.regex`. An invalid rule matches nothing — "does not contain" an empty
    /// text would otherwise take every episode.
    public var isValid: Bool {
        guard !pattern.trimmingCharacters(in: .whitespaces).isEmpty else { return false }
        return match != .regex || (try? NSRegularExpression(pattern: pattern)) != nil
    }
}

/// A subscription's rules, ready to test many episodes: expressions are
/// compiled once, and invalid rules left out.
public struct EpisodeRuleSet: Sendable {
    private let rules: [Compiled]

    public init(_ rules: [EpisodeRule]) {
        self.rules = rules.filter(\.isValid).map(Compiled.init)
    }

    public var isEmpty: Bool { rules.isEmpty }

    /// Whether any rule matches the episode, whatever it does.
    public func matches(_ episode: Episode) -> Bool {
        rules.contains { $0.test(episode.title) }
    }

    public func hides(_ episode: Episode) -> Bool {
        rules.contains { $0.action == .hide && $0.test(episode.title) }
    }

    public func marksPlayed(_ episode: Episode) -> Bool {
        rules.contains { $0.action == .markPlayed && $0.test(episode.title) }
    }

    private struct Compiled: @unchecked Sendable {
        let action: EpisodeRule.Action
        let match: EpisodeRule.Match
        let text: String
        let regex: NSRegularExpression?

        init(_ rule: EpisodeRule) {
            action = rule.action
            match = rule.match
            text = rule.pattern.trimmingCharacters(in: .whitespaces)
            regex = rule.match == .regex
                ? try? NSRegularExpression(pattern: rule.pattern, options: [.caseInsensitive])
                : nil
        }

        func test(_ title: String) -> Bool {
            switch match {
            case .contains:
                return title.containsLoosely(text)
            case .doesNotContain:
                return !title.containsLoosely(text)
            case .regex:
                guard let regex else { return false }
                return regex.firstMatch(in: title, range: NSRange(title.startIndex..., in: title)) != nil
            }
        }
    }
}

extension EpisodeRule {
    /// Texts to start a rule on episodes like `title` with: runs of its words
    /// (up to four) also found in other titles — but not in all of them, or the
    /// rule would take the whole show. The most shared come first.
    ///
    /// Several, because frequency alone cannot tell the show's name ("La
    /// riposte", in nearly every title) from what marks a series within it ("La
    /// chronique"): the user picks. A run inside a longer one shared just as
    /// much is left out — "chronique" behind "La chronique".
    public static func suggestedPatterns(for title: String, among titles: [String], limit: Int = 4) -> [String] {
        let words = title.split(whereSeparator: \.isWhitespace).map(String.init)
        let edges = CharacterSet.whitespaces.union(.punctuationCharacters).union(.symbols)
        var counts: [String: Int] = [:]
        for start in words.indices {
            for end in start..<min(start + 4, words.count) {
                let text = words[start...end].joined(separator: " ").trimmingCharacters(in: edges)
                guard text.count >= 4, counts[text] == nil else { continue }
                counts[text] = titles.filter { $0.containsLoosely(text) }.count
            }
        }
        let shared = counts.filter { $0.value >= 2 && $0.value < titles.count }
        let kept = shared.filter { text, count in
            !shared.contains { other, otherCount in
                otherCount == count && other.count > text.count && other.containsLoosely(text)
            }
        }
        return kept
            .sorted { ($0.value, $0.key.count) > ($1.value, $1.key.count) }
            .prefix(limit)
            .map(\.key)
    }
}

private extension String {
    /// Contains `other`, case and accents aside: "integrale" finds "L'Intégrale".
    func containsLoosely(_ other: String) -> Bool {
        range(of: other, options: [.caseInsensitive, .diacriticInsensitive]) != nil
    }
}
+13 −5
Changes for Packages/Core/Sources/StorageKit/LibraryStore+Browse.swift: 13 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -3,14 +3,22 @@ import GRDB
import PodcastModel

extension LibraryStore {
    /// Most recent episodes across all subscriptions (for the "Nouveautés" inbox).
    /// Most recent episodes across all subscriptions (for the "Nouveautés"
    /// inbox), leaving out those a rule hides — and reading on past them, so a
    /// show's many hidden chronicles do not cut the list short.
    public func recentEpisodes(limit: Int = 100) async throws -> [Episode] {
        try await dbQueue.read { db in
            try EpisodeRecord
            let rules = try Self.ruleSets(db)
            let records = try EpisodeRecord
                .order(Column("publicationDate").desc)
                .limit(limit)
                .fetchAll(db)
                .map { $0.toModel() }
                .fetchCursor(db)
            var episodes: [Episode] = []
            while episodes.count < limit, let record = try records.next() {
                let episode = record.toModel()
                if rules[record.podcastId]?.hides(episode) == true { continue }
                episodes.append(episode)
            }
            return episodes
        }
    }

+52
Changes for Packages/Core/Sources/StorageKit/LibraryStore+EpisodeRules.swift: 52 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import GRDB
import PodcastModel

extension LibraryStore {
    /// A subscription's episode rules, in the order they were added.
    public func episodeRules(forPodcastID id: UUID) async throws -> [EpisodeRule] {
        let podcastId = id.uuidString
        return try await dbQueue.read { db in
            try Self.rules(db, podcastId: podcastId)
        }
    }

    /// Every subscription's episode rules, keyed by podcast id.
    public func allEpisodeRules() async throws -> [UUID: [EpisodeRule]] {
        try await dbQueue.read { db in
            try EpisodeRuleRecord.order(Column("position")).fetchAll(db)
                .reduce(into: [UUID: [EpisodeRule]]()) { result, record in
                    if let id = UUID(uuidString: record.podcastId), let rule = record.toModel() {
                        result[id, default: []].append(rule)
                    }
                }
        }
    }

    /// Replaces a subscription's episode rules, keeping their order.
    public func setEpisodeRules(_ rules: [EpisodeRule], forPodcastID id: UUID) async throws {
        let podcastId = id.uuidString
        try await dbQueue.write { db in
            try EpisodeRuleRecord.filter(Column("podcastId") == podcastId).deleteAll(db)
            for (position, rule) in rules.enumerated() {
                try EpisodeRuleRecord(from: rule, podcastId: podcastId, position: position).insert(db)
            }
        }
    }

    static func rules(_ db: Database, podcastId: String) throws -> [EpisodeRule] {
        try EpisodeRuleRecord
            .filter(Column("podcastId") == podcastId)
            .order(Column("position"))
            .fetchAll(db)
            .compactMap { $0.toModel() }
    }

    /// Every subscription's rules, ready to test episodes, keyed by the
    /// podcast id as stored in the rows.
    static func ruleSets(_ db: Database) throws -> [String: EpisodeRuleSet] {
        let records = try EpisodeRuleRecord.order(Column("position")).fetchAll(db)
        return Dictionary(grouping: records, by: \.podcastId)
            .mapValues { EpisodeRuleSet($0.compactMap { $0.toModel() }) }
    }
}
Loading