From 25422b341142729fdc6f6d32b45e27986a3d535e Mon Sep 17 00:00:00 2001
From: Ozzie Isaacs <ozzie.fernandez.isaacs@googlemail.com>
Date: Sun, 12 Dec 2021 20:31:45 +0100
Subject: [PATCH] Fix for #2195 Sync token only updated after complete library
 sync and sync token content is discarded on first sync to enable real forced
 full sync

---
 cps/kobo.py | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/cps/kobo.py b/cps/kobo.py
index c5af44fc..e0395855 100644
--- a/cps/kobo.py
+++ b/cps/kobo.py
@@ -146,9 +146,16 @@ def HandleSyncRequest():
     if not current_app.wsgi_app.is_proxied:
         log.debug('Kobo: Received unproxied request, changed request port to external server port')
 
-    new_books_last_modified = sync_token.books_last_modified
-    new_books_last_created = sync_token.books_last_created
+    # if no books synced don't respect sync_token
+    if not ub.session.query(ub.KoboSyncedBooks).filter(ub.KoboSyncedBooks.user_id == current_user.id).count():
+        sync_token.books_last_modified = datetime.datetime.min
+        sync_token.books_last_created = datetime.datetime.min
+        sync_token.reading_state_last_modified = datetime.datetime.min
+
+    new_books_last_modified = sync_token.books_last_modified # needed for sync selected shelfs only
+    new_books_last_created = sync_token.books_last_created # needed to distinguish between new and changed entitlement
     new_reading_state_last_modified = sync_token.reading_state_last_modified
+
     new_archived_last_modified = datetime.datetime.min
     sync_results = []
 
@@ -306,11 +313,12 @@ def HandleSyncRequest():
 
     sync_shelves(sync_token, sync_results, only_kobo_shelves)
 
-    sync_token.books_last_created = new_books_last_created
+    # update last created timestamp to distinguish between new and changed entitlements
+    if not cont_sync:
+        sync_token.books_last_created = new_books_last_created
     sync_token.books_last_modified = new_books_last_modified
     sync_token.archive_last_modified = new_archived_last_modified
     sync_token.reading_state_last_modified = new_reading_state_last_modified
-    # sync_token.books_last_id = books_last_id
 
     return generate_sync_response(sync_token, sync_results, cont_sync)