Skip to content

Commit

Permalink
Only clear dirty bit after nodes are persisted
Browse files Browse the repository at this point in the history
  • Loading branch information
kiwiz committed Apr 13, 2024
1 parent d56a9e3 commit 64cc8dd
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 37 deletions.
25 changes: 18 additions & 7 deletions src/gkeepapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,9 @@ def login(
Raises:
LoginException: If there was a problem logging in.
"""
logger.warning("'Keep.login' is deprecated. Please use 'Keep.authenticate' instead")
logger.warning(
"'Keep.login' is deprecated. Please use 'Keep.authenticate' instead"
)
auth = APIAuth(self.OAUTH_SCOPES)
if device_id is None:
device_id = f"{get_mac():x}"
Expand All @@ -716,7 +718,9 @@ def resume(
sync: bool = True,
device_id: str | None = None,
) -> None:
logger.warning("'Keep.resume' has been renamed to 'Keep.authenticate'. Please update your code")
logger.warning(
"'Keep.resume' has been renamed to 'Keep.authenticate'. Please update your code"
)
self.authenticate(email, master_token, state, sync, device_id)

def authenticate(
Expand Down Expand Up @@ -1018,7 +1022,7 @@ def labels(self) -> list[_node.Label]:
"""
return list(self._labels.values())

def __UNSTABLE_API_uploadMedia(self, fh: IO)-> None:
def __UNSTABLE_API_uploadMedia(self, fh: IO) -> None:
pass

def getMediaLink(self, blob: _node.Blob) -> str:
Expand Down Expand Up @@ -1083,15 +1087,22 @@ def _sync_notes(self) -> None:
logger.debug("Starting keep sync: %s", self._keep_version)

# Collect any changes and send them up to the server.
labels_updated = any(i.dirty for i in self._labels.values())
updated_nodes = self._findDirtyNodes()
updated_labels = [l for l in self._labels.values() if l.dirty]
changes = self._keep_api.changes(
target_version=self._keep_version,
nodes=[i.save() for i in self._findDirtyNodes()],
labels=[i.save() for i in self._labels.values()]
if labels_updated
nodes=[i.save(False) for i in updated_nodes],
labels=[i.save(False) for i in self._labels.values()]
if updated_labels
else None,
)

# Clear
for node in updated_nodes:
node.save()
for label in updated_labels:
label.save()

if changes.get("forceFullResync"):
raise exception.ResyncRequiredException("Full resync required")

Expand Down
60 changes: 30 additions & 30 deletions src/gkeepapi/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def _load(self, raw: dict) -> None:
"""
self._dirty = raw.get("_dirty", False)

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Serialize into raw representation. Clears the dirty bit by default.
Args:
Expand All @@ -261,7 +261,7 @@ def save(self, clean: bool = True) -> dict:
ret = {}
if clean:
self._dirty = False
else:
elif clean is False:
ret["_dirty"] = self._dirty
return ret

Expand Down Expand Up @@ -289,7 +289,7 @@ def _load(self, raw: dict) -> None:
super()._load(raw)
self.id = raw.get("id")

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the annotation"""
ret = {}
if self.id is not None:
Expand All @@ -300,7 +300,7 @@ def save(self, clean: bool = True) -> dict:

@classmethod
def _generateAnnotationId(cls) -> str:
return "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}".format( # noqa: UP032
return "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}".format(
random.randint(0x00000000, 0xFFFFFFFF), # noqa: S311
random.randint(0x0000, 0xFFFF), # noqa: S311
random.randint(0x0000, 0xFFFF), # noqa: S311
Expand Down Expand Up @@ -331,7 +331,7 @@ def _load(self, raw: dict) -> None:
self._provenance_url = raw["webLink"]["provenanceUrl"]
self._description = raw["webLink"].get("description", self.description)

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the weblink"""
ret = super().save(clean)
ret["webLink"] = {
Expand Down Expand Up @@ -428,7 +428,7 @@ def _load(self, raw: dict) -> None:
super()._load(raw)
self._category = CategoryValue(raw["topicCategory"]["category"])

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the category annotation"""
ret = super().save(clean)
ret["topicCategory"] = {"category": self._category.value}
Expand Down Expand Up @@ -463,7 +463,7 @@ def _load(self, raw: dict) -> None:
super()._load(raw)
self._suggest = raw["taskAssist"]["suggestType"]

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the taskassist annotation"""
ret = super().save(clean)
ret["taskAssist"] = {"suggestType": self._suggest}
Expand Down Expand Up @@ -500,7 +500,7 @@ def _load(self, raw: dict) -> None:
for key, entry in raw.get("context", {}).items():
self._entries[key] = NodeAnnotations.from_json({key: entry})

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the context annotation"""
ret = super().save(clean)
context = {}
Expand Down Expand Up @@ -583,7 +583,7 @@ def _load(self, raw: dict) -> None:
annotation = self.from_json(raw_annotation)
self._annotations[annotation.id] = annotation

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the annotations container"""
ret = super().save(clean)
ret["kind"] = "notes#annotationsGroup"
Expand Down Expand Up @@ -697,7 +697,7 @@ def _load(self, raw: dict) -> None:
self.str_to_dt(raw["userEdited"]) if "userEdited" in raw else None
)

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the timestamps container"""
ret = super().save(clean)
ret["kind"] = "notes#timestamps"
Expand Down Expand Up @@ -858,7 +858,7 @@ def _load(self, raw: dict) -> None:
raw["checkedListItemsPolicy"]
)

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the settings container"""
ret = super().save(clean)
ret["newListItemPlacement"] = self._new_listitem_placement.value
Expand Down Expand Up @@ -936,7 +936,7 @@ def load(self, collaborators_raw: list, requests_raw: list) -> None: # noqa: D1
collaborator["type"]
)

def save(self, clean: bool = True) -> tuple[list, list]:
def save(self, clean: bool | None = True) -> tuple[list, list]:
"""Save the collaborators container"""
# Parent method not called.
collaborators = []
Expand All @@ -948,10 +948,10 @@ def save(self, clean: bool = True) -> tuple[list, list]:
collaborators.append(
{"email": email, "role": action.value, "auxiliary_type": "None"}
)
if not clean:
requests.append(self._dirty)
else:
if clean:
self._dirty = False
elif clean is False:
requests.append(self._dirty)
return (collaborators, requests)

def add(self, email: str) -> None:
Expand Down Expand Up @@ -1087,7 +1087,7 @@ def _load(self, raw: dict) -> None:
self.timestamps.load(raw["timestamps"])
self._merged = NodeTimestamps.str_to_dt(raw.get("lastMerged"))

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the label"""
ret = super().save(clean)
ret["mainId"] = self.id
Expand Down Expand Up @@ -1155,7 +1155,7 @@ def _load(self, raw: list) -> None:
for raw_label in raw:
self._labels[raw_label["labelId"]] = None

def save(self, clean: bool = True) -> tuple[dict] | tuple[dict, bool]: # noqa: D102
def save(self, clean: bool | None = True) -> tuple[dict] | tuple[dict, bool]: # noqa: D102
# Parent method not called.
ret = [
{
Expand All @@ -1168,10 +1168,10 @@ def save(self, clean: bool = True) -> tuple[dict] | tuple[dict, bool]: # noqa:
}
for label_id, label in self._labels.items()
]
if not clean:
ret.append(self._dirty)
else:
if clean:
self._dirty = False
elif clean is False:
ret.append(self._dirty)
return ret

def add(self, label: Label) -> None:
Expand Down Expand Up @@ -1258,7 +1258,7 @@ def __init__(

@classmethod
def _generateId(cls, tz: float) -> str:
return "{:x}.{:016x}".format( # noqa: UP032
return "{:x}.{:016x}".format(
int(tz * 1000),
random.randint(0x0000000000000000, 0xFFFFFFFFFFFFFFFF), # noqa: S311
)
Expand All @@ -1283,7 +1283,7 @@ def _load(self, raw: dict) -> None:
self.settings.load(raw["nodeSettings"])
self.annotations.load(raw["annotationsGroup"])

def save(self, clean: bool = True) -> dict: # noqa: D102
def save(self, clean: bool | None = True) -> dict: # noqa: D102
ret = super().save(clean)
ret["id"] = self.id
ret["kind"] = "notes#node"
Expand Down Expand Up @@ -1457,7 +1457,7 @@ def _load(self, raw: dict) -> None:
)
self._moved = "moved" in raw

def save(self, clean: bool = True) -> dict: # noqa: D102
def save(self, clean: bool | None = True) -> dict: # noqa: D102
ret = super().save(clean)
ret["color"] = self._color.value
ret["isArchived"] = self._archived
Expand Down Expand Up @@ -1605,7 +1605,7 @@ def _load(self, raw: dict) -> None:
self.super_list_item_id = raw.get("superListItemId") or None
self._checked = raw.get("checked", False)

def save(self, clean: bool = True) -> dict: # noqa: D102
def save(self, clean: bool | None = True) -> dict: # noqa: D102
ret = super().save(clean)
ret["parentServerId"] = self.parent_server_id
ret["superListItemId"] = self.super_list_item_id
Expand Down Expand Up @@ -1922,7 +1922,7 @@ def _load(self, raw: dict) -> None:
self._media_id = raw.get("media_id")
self._mimetype = raw.get("mimetype")

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the node blob"""
ret = super().save(clean)
ret["kind"] = "notes#blob"
Expand Down Expand Up @@ -1951,7 +1951,7 @@ def _load(self, raw: dict) -> None:
super()._load(raw)
self._length = raw.get("length")

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the node audio blob"""
ret = super().save(clean)
if self._length is not None:
Expand Down Expand Up @@ -2001,7 +2001,7 @@ def _load(self, raw: dict) -> None:
self._extracted_text = raw.get("extracted_text")
self._extraction_status = raw.get("extraction_status")

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the node image blob"""
ret = super().save(clean)
ret["width"] = self._width
Expand Down Expand Up @@ -2081,7 +2081,7 @@ def _load(self, raw: dict) -> None:
drawing_info.load(raw["drawingInfo"])
self._drawing_info = drawing_info

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the node drawing blob"""
ret = super().save(clean)
ret["extracted_text"] = self._extracted_text
Expand Down Expand Up @@ -2141,7 +2141,7 @@ def _load(self, raw: dict) -> None:
"snapshotProtoFprint", self._snapshot_proto_fprint
)

def save(self, clean: bool = True) -> dict: # noqa: D102
def save(self, clean: bool | None = True) -> dict: # noqa: D102
ret = super().save(clean)
ret["drawingId"] = self.drawing_id
ret["snapshotData"] = self.snapshot.save(clean)
Expand Down Expand Up @@ -2204,7 +2204,7 @@ def _load(self, raw: dict) -> None:
super()._load(raw)
self.blob = self.from_json(raw.get("blob"))

def save(self, clean: bool = True) -> dict:
def save(self, clean: bool | None = True) -> dict:
"""Save the blob"""
ret = super().save(clean)
if self.blob is not None:
Expand Down

0 comments on commit 64cc8dd

Please sign in to comment.