Skip to content

Commit

Permalink
refactor: adjust model struct
Browse files Browse the repository at this point in the history
  • Loading branch information
RedAtman committed Jun 25, 2024
1 parent 5da5e88 commit 1cafde3
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 121 deletions.
92 changes: 16 additions & 76 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,58 +23,12 @@ class _Note:
tags: List[str] = field(default_factory=list)
deleted: bool = False
shareURL: str = ""
publishURL: str = ""
content: str = ""
systemTags: List[str] = field(default_factory=list)
content: str = ""
publishURL: str = ""
modificationDate: float = field(default_factory=time.time)
creationDate: float = field(default_factory=time.time)

key: Optional[str] = ""
version: int = 0
modifydate: float = 0
createdate: float = 0
systemtags: List[str] = field(default_factory=list)
needs_update: Optional[bool] = None
local_modifydate: float = field(default_factory=time.time)
filename: Optional[str] = None

def __post_init__(self):
self._add_simplenote_api_fields()

def _add_simplenote_api_fields(self):
self.modifydate = self.modificationDate
self.createdate = self.creationDate
self.systemtags = self.systemTags

# def __setattr__(self, name: str, value: Any) -> None:
# if name in ["content", "tags", "systemTags"]:
# self.modificationDate = time.time()
# API.modify(self.__dict__)
# super().__setattr__(name, value)

# @property
# def key(self):
# if self._key:
# return self._key
# return self.id

# @key.setter
# def key(self, value):
# # self._key = uuid.uuid4().hex
# assert isinstance(value, str), "value is not a string: %s" % value
# assert len(value) == 32, "value length is not 32: %s" % value
# self._key = value

# @property
# def version(self):
# if self._version:
# return self._version
# return self.v

# @version.setter
# def version(self, value: int):
# self._version = value


class NoteType(TypedDict):
tags: List[str]
Expand All @@ -89,26 +43,27 @@ class NoteType(TypedDict):

@dataclass
class Note:
id: str = uuid.uuid4().hex
v: int = 0
d: _Note = field(default_factory=_Note)
id: Optional[str] = None

def _add_simplenote_api_fields(self):
self.d.key = self.id
self.d.version = self.v
modifydate: float = 0
createdate: float = 0
systemtags: List[str] = field(default_factory=list)
needs_update: Optional[bool] = None
local_modifydate: float = field(default_factory=time.time)
filename: Optional[str] = None

def _add_extra_fields(self):
self.modifydate = self.d.modificationDate
self.createdate = self.d.creationDate
self.systemtags = self.d.systemTags

def __post_init__(self):
# print((type(self.d), self.d))
if self.id is None:
self.id = uuid.uuid4().hex
if isinstance(self.d, dict):
d = _Note(**self.d)
# status, note = API.modify(self.d.__dict__)
# logger.info((status, note))
# assert status == 0, "Error Create note"
# assert isinstance(note, dict)
self.d = d
self._add_simplenote_api_fields()
self._add_extra_fields()

def _nest_dict(self) -> Dict:
result = self.__dict__
Expand All @@ -118,19 +73,6 @@ def _nest_dict(self) -> Dict:
def __eq__(self, value: "Note") -> bool:
return self.id == value.id and self.v == value.v

# def __setattr__(self, name: str, value: Any) -> None:
# print(f"__setattr__({name}, {value})")
# super().__setattr__(name, value)

# def __getattribute__(self, name: str) -> Any:
# value = None
# try:
# value = super().__getattribute__(name)
# except AttributeError:
# value = getattr(self.d, name)
# # print(f"__getattribute__({name})", value)
# return value

@staticmethod
def index(limit: int = CONFIG.NOTE_FETCH_LENGTH, data: bool = True) -> List["Note"]:
status, result = API.index(limit, data)
Expand All @@ -155,14 +97,12 @@ def create(self) -> "Note":
status, _note = API.modify(self.d.__dict__, self.id)
assert status == 0, "Error creating note"
assert isinstance(_note, dict)
assert self.id == _note["id"]
return self

# def update(self, **kwargs: Unpack[NoteType]):
def modify(self, version: Optional[int] = None) -> "Note":
# note = _Note(**kwargs)
# TODO: maybe do not need to update the modificationDate here
self.d.modificationDate = time.time()
# self.d.content += "\n\n" + kwargs.get("content", "")
status, _note = API.modify(self.d.__dict__, self.id, version)
assert status == 0, "Error updating note"
assert isinstance(_note, dict)
Expand Down
4 changes: 2 additions & 2 deletions operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,9 @@ def run(self):
threads: List[Thread] = []
for current_note in self.notes:
assert isinstance(current_note, Note)
assert isinstance(current_note.d.key, str)
assert isinstance(current_note.id, str)
new_thread = NoteDownloader(
current_note.d.key,
current_note.id,
self.semaphore,
sm=self.sm,
)
Expand Down
35 changes: 10 additions & 25 deletions simplenote.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@ def get_filename_for_note(title_extension_map: List[Dict], note: Note) -> str:
if re.search(pattern, note_name):
extension = "." + item["extension"]
break
# logger.info(("extension", extension, "base", base, "note_name", note_name, "note.d.key", note.d.key))
return base + " (" + note.d.key + ")" + extension
# logger.info(("extension", extension, "base", base, "note_name", note_name, "note.id", note.id))
return base + " (" + note.id + ")" + extension

# @classmethod
def _get_filename_for_note(cls, note: Note) -> str:
Expand Down Expand Up @@ -275,26 +275,14 @@ def __ne__(self, other):
return K


def sort_notes(a_note, b_note):
if isinstance(a_note, Note):
a_systemtags = a_note.d.systemtags
a_modifydate = a_note.d.modifydate
else:
a_systemtags = a_note["systemtags"]
a_modifydate = a_note["modifydate"]
if isinstance(b_note, Note):
b_systemtags = b_note.d.systemtags
b_modifydate = b_note.d.modifydate
else:
b_systemtags = b_note["systemtags"]
b_modifydate = b_note["modifydate"]
if "pinned" in a_systemtags:
def sort_notes(a_note: Note, b_note: Note):
if "pinned" in a_note.systemtags:
return 1
elif "pinned" in b_systemtags:
elif "pinned" in b_note.systemtags:
return -1
else:
date_a = datetime.fromtimestamp(float(a_modifydate))
date_b = datetime.fromtimestamp(float(b_modifydate))
date_a = datetime.fromtimestamp(float(a_note.modifydate))
date_b = datetime.fromtimestamp(float(b_note.modifydate))
return (date_a > date_b) - (date_a < date_b)


Expand Down Expand Up @@ -380,9 +368,6 @@ def handle_open_filename_change(old_file_path, updated_note: Note):

def synch_note_resume(existing_note_entry: Note, updated_note_resume: Note):
for key in updated_note_resume.d.__dict__:
# TODO: remove this
if key == "filename":
continue
# logger.info(("key", key, getattr(updated_note_resume.d, key)))
setattr(existing_note_entry.d, key, getattr(updated_note_resume.d, key))

Expand All @@ -395,8 +380,8 @@ def update_note(existing_note: Note, updated_note: Note):
# filename = sm.local._get_filename_for_note(existing_note)
# logger.info(("Updating note", "filename", filename, "existing_note", existing_note))
# existing_note["filename"] = filename
existing_note.d.local_modifydate = time.time()
existing_note.d.needs_update = False
existing_note.local_modifydate = time.time()
existing_note.needs_update = False
filename = sm.local._get_filename_for_note(existing_note)
# logger.info(("Updating note", "filename", filename, "existing_note", existing_note))
existing_note.d.filename = filename
existing_note.filename = filename
36 changes: 18 additions & 18 deletions simplenotecommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def flush_saves():
return

for entry in HandleNoteViewCommand.waiting_to_save:
if entry["note_key"] == note.d.key:
if entry["note_key"] == note.id:

with entry["lock"]:
entry["count"] = entry["count"] - 1
Expand All @@ -88,14 +88,14 @@ def flush_saves():

found = False
for entry in HandleNoteViewCommand.waiting_to_save:
if entry["note_key"] == note.d.key:
if entry["note_key"] == note.id:
with entry["lock"]:
entry["count"] = entry["count"] + 1
found = True
break
if not found:
new_entry = {}
new_entry["note_key"] = note.d.key
new_entry["note_key"] = note.id
new_entry["lock"] = Lock()
new_entry["count"] = 1
HandleNoteViewCommand.waiting_to_save.append(new_entry)
Expand Down Expand Up @@ -123,7 +123,7 @@ def handle_note_changed(
# We get all the resume data back. We have to merge it
# with our data (extended fields and content)
for note in sm.local.objects:
if note.d.key == modified_note_resume.d.key:
if note.id == modified_note_resume.id:
# Set content to the updated one
# or to the view's content if we don't have any update
updated_from_server = False
Expand Down Expand Up @@ -216,7 +216,7 @@ def merge_delta(self, updated_note_resume: List[Note], existing_notes: List[Note
for current_updated_note_resume in updated_note_resume:
existing_note_entry = None
for existing_note in existing_notes:
if existing_note.d.key == current_updated_note_resume.d.key:
if existing_note.id == current_updated_note_resume.id:
existing_note_entry: Note = existing_note
break

Expand All @@ -226,31 +226,31 @@ def merge_delta(self, updated_note_resume: List[Note], existing_notes: List[Note
# Mark for update if needed
try:
# Note with old content
if existing_note_entry.d.local_modifydate < float(current_updated_note_resume.d.modifydate):
if existing_note_entry.local_modifydate < float(current_updated_note_resume.modifydate):
synch_note_resume(existing_note_entry, current_updated_note_resume)
existing_note_entry.d.needs_update = True
existing_note_entry.needs_update = True
logger.info(("existing_note_entry", existing_note_entry))
else:
# Up to date note
existing_note_entry.d.needs_update = False
existing_note_entry.needs_update = False
except KeyError as err:
logger.exception(err)
# Note that never got the content downloaded:
existing_note_entry.d.needs_update = True
existing_note_entry.needs_update = True

logger.info(("existing_note_entry", existing_note_entry))
# New note
else:
# new_note_entry = {"needs_update": True}
# synch_note_resume(new_note_entry, current_updated_note_resume)
# existing_notes.append(new_note_entry)
current_updated_note_resume.d.needs_update = True
current_updated_note_resume.needs_update = True
existing_notes.append(current_updated_note_resume)

# Look at the existing notes to find deletions
updated_note_resume_keys = [note.d.key for note in updated_note_resume]
updated_note_resume_keys = [note.id for note in updated_note_resume]
deleted_notes = [
deleted_note for deleted_note in existing_notes if deleted_note.d.key not in updated_note_resume_keys
deleted_note for deleted_note in existing_notes if deleted_note.id not in updated_note_resume_keys
]
for deleted_note in deleted_notes:
existing_notes.remove(deleted_note)
Expand Down Expand Up @@ -290,11 +290,11 @@ def notes_synch(self, notes: List[Note]):
others: List[Note] = []
for note in notes:

if not note.d.needs_update:
if not note.needs_update:
continue

try:
filename = note.d.filename
filename = note.filename
except KeyError as err:
logger.exception(err)
others.append(note)
Expand Down Expand Up @@ -349,7 +349,7 @@ def merge_open(self, updated_notes: List[Note], existing_notes: List[Note], dirt
for note in existing_notes:
for updated_note in updated_notes:
# If we find the updated note
if note.d.key == updated_note.d.key:
if note.id == updated_note.id:
old_file_path = sm.local.get_path_for_note(note)
new_file_path = sm.local.get_path_for_note(updated_note)
# Update contents
Expand All @@ -371,12 +371,12 @@ def merge_notes(self, updated_notes: List[Note], existing_notes: List[Note]):
# Merge
for note in existing_notes:

if not note.d.needs_update:
if not note.needs_update:
continue

for updated_note in updated_notes:
try:
if note.d.key == updated_note.d.key:
if note.id == updated_note.id:
update_note(note, updated_note)
except KeyError as err:
logger.exception(err)
Expand Down Expand Up @@ -491,7 +491,7 @@ def plugin_loaded():
# sm.local.load_notes()
if len(sm.local.objects):
logger.info(("Loaded notes: ", sm.local.objects[0]))
note_files = [note.d.filename for note in sm.local.objects]
note_files = [note.filename for note in sm.local.objects]
if not os.path.exists(TEMP_PATH):
os.makedirs(TEMP_PATH)
for f in os.listdir(TEMP_PATH):
Expand Down

0 comments on commit 1cafde3

Please sign in to comment.