Skip to content

fix(sync): append offline liked songs to youtube instead of overwriting#3935

Open
kairosci wants to merge 3 commits into
MetrolistGroup:mainfrom
kairosci:fix-local-liked-songs-overwrite
Open

fix(sync): append offline liked songs to youtube instead of overwriting#3935
kairosci wants to merge 3 commits into
MetrolistGroup:mainfrom
kairosci:fix-local-liked-songs-overwrite

Conversation

@kairosci

@kairosci kairosci commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Problem

Local liked songs are getting overwritten by the YouTube account liked songs when a user logs in, effectively wiping out their offline likes.

Cause

The sync logic in SyncUtils was removing local likes for any songs not present in the remote YouTube list, without accounting for songs that were liked while the user was offline or prior to logging in.

Solution

  • Checked the LastFullSyncKey timestamp to determine if a local like was added after the last sync or while offline.
  • Pushed offline likes to YouTube during sync, appending them to the account instead of overwriting them.
  • Ignored local device files (isLocal) during the sync so they are never unliked by the YouTube remote state.

Testing

Analyzed and tested the sync algorithm to ensure offline likes are preserved and pushed, while still respecting unlikes made remotely.

Related Issues

Summary by CodeRabbit

  • Bug Fixes
    • Improved synchronization of liked songs between local and remote libraries: local-only likes are no longer removed during cleanup. Instead, qualifying local likes are pushed to the remote list.
    • Tightened merge/update behavior to apply changes more selectively, helping preserve existing like timestamps when appropriate and keeping video status aligned with the remote source.
    • Enhanced completion reporting to include both remote and local liked song counts for clearer sync results.

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 91ffc19e-fd89-41f5-8b82-e37f176ff388

📥 Commits

Reviewing files that changed from the base of the PR and between 218b0b7 and fedbc2c.

📒 Files selected for processing (1)
  • app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt

📝 Walkthrough

Walkthrough

The PR updates the liked songs sync logic in SyncUtils.kt to implement bidirectional reconciliation. Instead of removing local likes for songs absent from the remote YouTube liked list, the sync now pushes local-only liked songs to YouTube (excluding locally-owned songs), then pulls remote likes back into the local database with a narrowed update condition that preserves existing likedDate values. The completion log reports both remote and local liked song counts.

Changes

Liked Songs Bidirectional Sync Reconciliation

Layer / File(s) Summary
Push local-only likes to YouTube, then pull remote likes locally
app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt
Local-only liked songs are pushed to YouTube (excluding song.isLocal entries), then remote liked songs are pulled into the local database only when the local record is not currently liked, preserving existing likedDate values. Completion log updated to include both remote and local liked song counts.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • nyxiereal
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: preventing offline liked songs from being overwritten by appending them to YouTube instead.
Description check ✅ Passed The PR description includes all required sections (Problem, Cause, Solution, Testing, Related Issues) with sufficient detail explaining the data loss issue and the implemented fix.
Linked Issues check ✅ Passed The PR successfully addresses issue #3685 by implementing logic to append offline liked songs to YouTube instead of overwriting them, and respecting the isLocal flag to prevent device-specific likes from being removed.
Out of Scope Changes check ✅ Passed All changes in SyncUtils.kt are directly related to resolving the offline liked songs overwrite issue; no out-of-scope modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@kairosci

kairosci commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

@suicedia could you verify this solves your problem? Thanks

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt`:
- Line 678: This path directly calls YouTube.likeVideo(song.id, true) without
retries; wrap that call in the same withRetry { ... } used by executeLikeSong()
so transient YouTube API failures are retried, and only update/log local state
on success/final failure as executeLikeSong() does (mirror its error handling
and logging behavior referenced around executeLikeSong() and the existing log at
the current YouTube.likeVideo(...) usage).
- Around line 674-681: The loop in SyncUtils.kt that processes
localSongs.filterNot { it.id in remoteIds || it.song.isLocal } must not call
database.update(song.song.localToggleLike()) when song.song.likedDate == null
because migrated legacy rows can have liked=true with a NULL likedDate; instead
treat null as preserved/backfill-needed: change the branch so that if likedDate
== null you either call YouTube.likeVideo(song.id, true) to ensure remote
like/backfill or simply skip toggling the local like (no database.update), and
leave a TODO/comment to schedule a migration/backfill job; modify the condition
around YouTube.likeVideo(song.id, true) / database.update(...) accordingly
(identify the variables song.song.likedDate, YouTube.likeVideo, database.update,
localToggleLike, localSongs, remoteIds).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 12a957b5-b61a-4b0d-83d7-a6dbcc17a541

📥 Commits

Reviewing files that changed from the base of the PR and between b52c585 and 39631da.

📒 Files selected for processing (1)
  • app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt

Comment thread app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt Outdated
Comment thread app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt (1)

671-683: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

LastFullSyncKey is being compared against the wrong sync boundary.

Line 671 assumes this key still represents the previous successful full sync, but tryAutoSync() updates it before the queued sync even runs. That means an offline like created after the last real sync can already be older than lastSync by the time this loop executes, so Line 685 will unlike it locally instead of pushing it to YouTube. Move the LastFullSyncKey write to the end of a successful executeFullSync() so this branch compares against the last completed sync, not the current attempt.

♻️ Minimal fix direction
 fun tryAutoSync() {
     syncScope.launch {
         ...
         syncChannel.send(SyncOperation.FullSync)
-
-        context.dataStore.edit { settings ->
-            settings[LastFullSyncKey] = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)
-        }
     }
 }

 private suspend fun executeFullSync() = withContext(Dispatchers.IO) {
     ...
     try {
         ...
         executeSyncAutoSyncPlaylists()

+        context.dataStore.edit { settings ->
+            settings[LastFullSyncKey] = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)
+        }
         updateState { copy(overallStatus = SyncStatus.Completed, currentOperation = "") }
     } catch (e: CancellationException) {
         throw e
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt` around lines 671
- 683, The code is comparing likes against LastFullSyncKey which is being set
too early; change the flow so LastFullSyncKey represents the last completed full
sync by removing/updating any write to LastFullSyncKey in tryAutoSync() and
instead writing LastFullSyncKey at the end of executeFullSync() only after a
successful completion; ensure the filter/compare that reads LastFullSyncKey (the
localSongs loop that references lastSync) continues to read from
context.dataStore.get(LastFullSyncKey, 0L) so it now compares against the
previous completed sync boundary.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt`:
- Around line 671-683: The code is comparing likes against LastFullSyncKey which
is being set too early; change the flow so LastFullSyncKey represents the last
completed full sync by removing/updating any write to LastFullSyncKey in
tryAutoSync() and instead writing LastFullSyncKey at the end of
executeFullSync() only after a successful completion; ensure the filter/compare
that reads LastFullSyncKey (the localSongs loop that references lastSync)
continues to read from context.dataStore.get(LastFullSyncKey, 0L) so it now
compares against the previous completed sync boundary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3458e504-2788-41f7-908c-fecd281ca5c5

📥 Commits

Reviewing files that changed from the base of the PR and between 39631da and 624c3f5.

📒 Files selected for processing (1)
  • app/src/main/kotlin/com/metrolist/music/utils/SyncUtils.kt

@kairosci kairosci force-pushed the fix-local-liked-songs-overwrite branch from cbb370d to 218b0b7 Compare June 20, 2026 09:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Local liked songs overwritten by YouTube account liked songs

1 participant