Commit 2ca810fc authored by Kourser's avatar Kourser
Browse files

fix(sync): positions that keep the newest, find their episode, and travel at once

Prompted by a user asking for play-position sync between an iPhone and an
iPad — which the app already advertised, but did badly.

The newest position now wins. Every sync sent the whole history, each
position stamped with the moment it was sent: a device that had not
played an episode for a week sent its old position as the newest, and
received positions overwrote local ones without comparison. Positions
now travel with the moment they were listened to (playstate.updatedAt,
recorded all along); only those changed since the last sent go out, and
a received one is applied only when newer than the local one. A position
received keeps its original date, so it does not bounce back as new. A
pause that does not move the position no longer re-dates it.

Episodes are found. Received positions were matched on the exact media
address, which some hosts suffix with a token that changes at every
fetch of the feed (audiomeans: "?_=1790612786"). Matching now goes by
the guid, then by the address without its query — the rule Handoff used,
moved to Episode so both share it — within the feed the action names.

Positions travel at once. They went out with the full sync, at most
every 30 minutes on launch or return. Now they are exchanged on their
own, light: after a pause, at the end of an episode, when an episode is
marked played, and on leaving the app (with background time on iOS,
which would otherwise suspend it mid-request); and received on every
return to the app. Exchanges never overlap. The full sync is unchanged
otherwise; when it subscribes this device to podcasts from the server,
it reads all positions again, since those for podcasts it did not follow
yet were set aside. Light exchanges wait for that first full sync.

Réglages › Synchronisation shows when positions were last exchanged.
A DEBUG-only `-uiSyncPassword` launch argument fills the password for
testing against a local server, the Simulator's field refusing pasted text.

Verified on two iOS 27 simulators, iPhone and a fresh iPad, against a
local stand-in for Nextcloud's GPodder Sync app: the iPad, on its first
launch, subscribed and picked up the iPhone's positions with their
original dates; a pause on the iPhone sent 41 s dated at the pause, and
the iPad had it on coming back to the foreground. 11 new tests cover the
merge, the matching, the dates servers send and the store query. Not
tried: a real Nextcloud or gpodder.net server, and gpodder.net at all.

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

## [Non publié]

### Corrigé
- **Synchronisation de la position de lecture** (Nextcloud et gpodder.net) :
  - une position plus ancienne pouvait écraser la plus récente. Chaque position
    voyage désormais avec l'heure à laquelle elle a été écoutée, et chaque
    appareil garde la plus récente ;
  - les épisodes dont l'hébergeur ajoute un paramètre changeant à l'adresse du
    fichier audio n'étaient jamais reconnus ; ils le sont, par leur identifiant
    dans le flux ou par l'adresse sans ce paramètre ;
  - la position ne partait qu'à la synchronisation, au plus toutes les 30
    minutes. Elle part maintenant à chaque pause, en fin d'épisode et en
    quittant l'app, et les positions des autres appareils arrivent à chaque
    retour dans l'app ;
  - un nouvel appareil récupère les positions des podcasts qu'il découvre lors
    de sa première synchronisation.
  Réglages › Synchronisation indique quand les positions ont été synchronisées
  pour la dernière fois.

## [1.2.0] - 2026-09-30

### Ajouté
+2 −2
Changes for Packages/Core/Package.swift: 2 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -49,7 +49,7 @@ let package = Package(
        .target(name: "DiscoveryKit"),

        // Subscription sync with Nextcloud (GPodder Sync) and gpodder.net.
        .target(name: "SyncKit"),
        .target(name: "SyncKit", dependencies: ["PodcastModel"]),

        .testTarget(
            name: "FeedKitTests",
@@ -70,7 +70,7 @@ let package = Package(
        ),
        .testTarget(
            name: "SyncKitTests",
            dependencies: ["SyncKit"]
            dependencies: ["SyncKit", "PodcastModel"]
        ),
    ],
    // Match the app's Swift 5 language mode; keeps AVPlayer/observer wiring
+2 −16
Changes for Packages/Core/Sources/PlaybackKit/ListeningHandoff.swift: 2 added lines, 16 removed lines.
Original line number Diff line number Diff line
@@ -48,22 +48,8 @@ public struct ListeningHandoff: Equatable, Sendable {

    // MARK: Matching

    /// The episode it designates among those of its feed. The `guid` decides
    /// when there is one; otherwise the media address, compared without its
    /// query — hosts append tokens there that change from one fetch to the
    /// next.
    /// The episode it designates among those of its feed.
    public func episode(in episodes: [Episode]) -> Episode? {
        if let guid, let match = episodes.first(where: { $0.guid == guid }) {
            return match
        }
        guard let wanted = enclosureURL.map(Self.withoutQuery) else { return nil }
        return episodes.first { $0.enclosureURL.map(Self.withoutQuery) == wanted }
    }

    private static func withoutQuery(_ url: URL) -> String {
        var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
        components?.query = nil
        components?.fragment = nil
        return components?.string ?? url.absoluteString
        Episode.matching(guid: guid, enclosureURL: enclosureURL, in: episodes)
    }
}
+42
Changes for Packages/Core/Sources/PodcastModel/EpisodeMatching.swift: 42 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation

extension Episode {
    /// The episode among `episodes` that another device — or another podcast
    /// app — means. Libraries do not share identifiers, so an episode is named
    /// by what its feed says of it: the guid decides when there is one;
    /// otherwise the media address, compared without its query, where hosts
    /// append tokens that change from one fetch of the feed to the next.
    public static func matching(guid: String?, enclosureURL: URL?, in episodes: [Episode]) -> Episode? {
        if let guid, let match = episodes.first(where: { $0.guid == guid }) {
            return match
        }
        guard let wanted = enclosureURL.map(mediaKey) else { return nil }
        return episodes.first { $0.enclosureURL.map(mediaKey) == wanted }
    }

    private static func mediaKey(_ url: URL) -> String {
        var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
        components?.query = nil
        components?.fragment = nil
        return components?.string ?? url.absoluteString
    }
}

/// Where an episode was left, and when — what position sync exchanges with
/// other devices. The date is the point: it is what lets each device keep the
/// newest position rather than the last one to arrive.
public struct EpisodeProgress: Sendable, Equatable {
    public var episode: Episode
    public var feedURL: URL
    public var position: TimeInterval
    public var isPlayed: Bool
    public var updatedAt: Date

    public init(episode: Episode, feedURL: URL, position: TimeInterval, isPlayed: Bool, updatedAt: Date) {
        self.episode = episode
        self.feedURL = feedURL
        self.position = position
        self.isPlayed = isPlayed
        self.updatedAt = updatedAt
    }
}
+29 −38
Changes for Packages/Core/Sources/StorageKit/LibraryStore+PlayState.swift: 29 added lines, 38 removed lines.
Original line number Diff line number Diff line
@@ -43,51 +43,42 @@ extension LibraryStore {
        }
    }

    /// Finds a stored episode by its media (enclosure) URL — used to apply
    /// remote episode actions during sync.
    public func episode(withEnclosureURL url: URL) async throws -> Episode? {
    /// Play progress changed after `cutoff` — all of it when `nil` — with the
    /// episode and feed that identify it to another device. For position sync.
    public func playProgress(changedAfter cutoff: Date?) async throws -> [EpisodeProgress] {
        try await dbQueue.read { db in
            try EpisodeRecord
                .filter(Column("enclosureURL") == url.absoluteString)
                .fetchOne(db)?
                .toModel()
            var request = PlayStateRecord.all()
            if let cutoff {
                request = request.filter(Column("updatedAt") > cutoff.timeIntervalSince1970)
            }
            let states = try request.fetchAll(db)
            guard !states.isEmpty else { return [] }
            let episodes = try EpisodeRecord.filter(keys: states.map(\.episodeId)).fetchAll(db)
            let feeds = try PodcastRecord.filter(keys: Set(episodes.map(\.podcastId)).sorted()).fetchAll(db)
                .reduce(into: [String: URL]()) { $0[$1.id] = URL(string: $1.feedURL) }
            let episodesByID = Dictionary(episodes.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
            return states.compactMap { state in
                guard let record = episodesByID[state.episodeId],
                      let feedURL = feeds[record.podcastId] else { return nil }
                return EpisodeProgress(
                    episode: record.toModel(),
                    feedURL: feedURL,
                    position: state.position,
                    isPlayed: state.isPlayed,
                    updatedAt: Date(timeIntervalSince1970: state.updatedAt)
                )
            }
        }
    }

    /// Local play progress joined with feed/media URLs, for episode-action sync.
    public func playProgressForSync() async throws -> [EpisodeProgress] {
    /// When each episode's progress last changed, keyed by episode id.
    public func playStateDates() async throws -> [UUID: Date] {
        try await dbQueue.read { db in
            let rows = try Row.fetchAll(db, sql: """
                SELECT podcast.feedURL AS feedURL, episode.enclosureURL AS enclosureURL,
                       playstate.position AS position, episode.duration AS total,
                       playstate.isPlayed AS isPlayed
                FROM playstate
                JOIN episode ON episode.id = playstate.episodeId
                JOIN podcast ON podcast.id = episode.podcastId
                WHERE episode.enclosureURL IS NOT NULL
                """)
            return rows.compactMap { row -> EpisodeProgress? in
                let feedString: String? = row["feedURL"]
                let enclosureString: String? = row["enclosureURL"]
                guard let feed = feedString.flatMap(URL.init(string:)),
                      let enclosure = enclosureString.flatMap(URL.init(string:)) else { return nil }
                let position: Double = row["position"] ?? 0
                let total: Double? = row["total"]
                let isPlayed: Bool = row["isPlayed"] ?? false
                return EpisodeProgress(
                    feedURL: feed, enclosureURL: enclosure,
                    position: position, total: total, isPlayed: isPlayed
                )
            try PlayStateRecord.fetchAll(db).reduce(into: [UUID: Date]()) { result, record in
                if let id = UUID(uuidString: record.episodeId) {
                    result[id] = Date(timeIntervalSince1970: record.updatedAt)
                }
            }
        }
    }

/// Local play progress with the URLs needed to build a sync episode action.
public struct EpisodeProgress: Sendable, Equatable {
    public var feedURL: URL
    public var enclosureURL: URL
    public var position: TimeInterval
    public var total: TimeInterval?
    public var isPlayed: Bool
}
Loading