Skip to content

Commit

Permalink
Improved code quality
Browse files Browse the repository at this point in the history
Added some comments where needed
  • Loading branch information
Wemmy0 committed Feb 18, 2024
1 parent 9d762b0 commit a7fde63
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 45 deletions.
3 changes: 2 additions & 1 deletion src/FileView.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def add_note(self, *args):
self.creating_new = True # Block the user from creating another note whilst making another

def create_new_note(self, *args):
# Please don't look at this line
filename = self.path + "/" + self.file_viewer.get_last_child().get_last_child().get_first_child().get_text() + ".json"
self.file_viewer.json_data[filename] = self.file_viewer.palette[0]
self.file_viewer.remove(self.get_last_child().get_last_child())
Expand Down Expand Up @@ -229,7 +230,7 @@ def change_colour(self, container, row):

def initialise_json(filename):
# If json file isn't found, create it with json {}
print(f"{filename} doesn't exist. Creating")
log(f"{filename} doesn't exist. Creating")
with open(filename, "w+") as file:
file.write("{}")

Expand Down
40 changes: 26 additions & 14 deletions src/NoteView.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ def edit_style(element, mode):
class NoteView(Gtk.Box):
def __init__(self, config, ai_config, read_only, header):
super().__init__(orientation=Gtk.Orientation.VERTICAL)
self.objects = None
self.filename = None
self.config = config
self.ai_config = ai_config
self.read_only = read_only
Expand All @@ -38,6 +40,7 @@ def remove_all(self):
self.children = []

def change_file(self, filename):
# Purpose: Called to change the file to view
self.filename = filename
self.remove_all()

Expand Down Expand Up @@ -67,7 +70,6 @@ def add_element(self, data, loading_file=False):
edit_style(element, True)

def undo(self, *args):
print("Undoing...")
self.remove(self.history.pop())

if self.history.is_empty():
Expand Down Expand Up @@ -165,8 +167,16 @@ def can_move(self):


class Element(Gtk.Box):
# Purpose: A general 'harness' to
def __init__(self, data, config, ai_config, read_only):
super().__init__()
self.ai_dialogue = None
self.ai_container = None
self.ai_btn = None
self.up_btn = None
self.del_btn = None
self.down_btn = None
self.controls = None
self.container = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.data = data
self.config = config
Expand All @@ -179,23 +189,28 @@ def __init__(self, data, config, ai_config, read_only):
try:
match self.data["type"]:
case "title":
if config["title"]: self.main = Title(self.data, read_only)
if config["title"]:
self.main = Title(self.data, read_only)
self.container.append(self.main)

case "body":
if config["body"]: self.main = Body(self.data, read_only)
if config["body"]:
self.main = Body(self.data, read_only)
self.container.append(self.main)

case "image":
if config["image"]: self.main = Image(self.data)
if config["image"]:
self.main = Image(self.data)
self.container.append(self.main)

case "list":
if config["list"]: self.main = List(self.data)
if config["list"]:
self.main = List(self.data)
self.container.append(self.main)

case "task":
if config["task"]: self.main = Task(self.data)
if config["task"]:
self.main = Task(self.data)
self.container.append(self.main)

case _:
Expand Down Expand Up @@ -329,7 +344,6 @@ def __init__(self, data):
super().__init__(css_name="item-list", margin_start=5)
self.children = []
self.main = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
# self.main = Gtk.ListBox(css_name="item-list", selection_mode=Gtk.SelectionMode.NONE)
for item in data["items"]:
item = ListItem(item)
item.main.connect("activate", self.add_item)
Expand All @@ -344,7 +358,6 @@ def backspace_item(self, widget):

def add_item(self, widget: Gtk.Entry):
if widget.get_text(): # Prevents new tasks being added when last task is empty
# item.main.connect("backspace", self.backspace_item)
removed = []
while True:
next = self.main.get_last_child()
Expand Down Expand Up @@ -386,7 +399,6 @@ def __init__(self, data):
super().__init__(css_name="item-list", margin_start=0)
self.children = []
self.main = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
# self.main = Gtk.ListBox(css_name="item-list", selection_mode=Gtk.SelectionMode.NONE)
for item in data["items"]:
if type(item) == list:
self.add_item(task=item)
Expand Down Expand Up @@ -440,11 +452,11 @@ def save(self):


def set_margins(widget, num):
def margins(x, num):
x.set_margin_start(num)
x.set_margin_end(num)
x.set_margin_top(num)
x.set_margin_bottom(num)
def margins(x, margin):
x.set_margin_start(margin)
x.set_margin_end(margin)
x.set_margin_top(margin)
x.set_margin_bottom(margin)

if type(widget) == list:
for i in widget:
Expand Down
1 change: 1 addition & 0 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def __init__(self, *args, **kwargs):
class MyApp(Adw.Application):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.win = None
load_configuration()
self.sync = Sync(config, False)
self.connect('activate', self.on_activate)
Expand Down
47 changes: 24 additions & 23 deletions src/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ def __init__(self, config, verbose):

self.do()

def log(self, *args):
if self.verbose:
print(*args)

def convert_to_blob(self, filename):
with open(filename, 'rb') as file:
blob_data = file.read()
Expand All @@ -47,32 +43,32 @@ def compare_files(self, file):
self.cursor.execute(f"SELECT hash FROM test WHERE filename = %s", (file,))
db_hash = self.cursor.fetchall()[0][0]
local_hash = self.hash_file(file)
self.log("=" * 20 + file + "=" * 20)
self.log(f"Local Hash: {local_hash}")
self.log(f"DB Hash: {db_hash}")
log("=" * 20 + file + "=" * 20)
log(f"Local Hash: {local_hash}")
log(f"DB Hash: {db_hash}")

if local_hash == db_hash:
self.log("Hashes match, skipping file")
log("Hashes match, skipping file")
self.skipped += 1
else:
self.log("Hashes don't match, checking timestamps")
log("Hashes don't match, checking timestamps")
self.cursor.execute(f"SELECT modified FROM test WHERE filename = %s", (file,))
db_timestamp = int(self.cursor.fetchall()[0][0])
local_timestamp = round(os.path.getctime(file))
self.log(f"Local timestamp: {local_timestamp}")
self.log(f"DB timestamp: {db_timestamp}")
log(f"Local timestamp: {local_timestamp}")
log(f"DB timestamp: {db_timestamp}")

if local_timestamp > db_timestamp:
self.log("Local file is newer, uploading")
log("Local file is newer, uploading")
self.update_file(file, local_timestamp, local_hash)

elif local_timestamp < db_timestamp:
self.log("Local file is older, downloading")
log("Local file is older, downloading")
self.download_file(file)
else:
self.log("Timestamps match, skipping")
log("Timestamps match, skipping")
self.skipped += 1
self.log("=" * (40 + len(file)))
log("=" * (40 + len(file)))

def update_file(self, file, time, hash):
try:
Expand All @@ -83,7 +79,7 @@ def update_file(self, file, time, hash):
self.connection.commit()
self.uploaded += 1
except mysql.connector.errors.DataError:
self.log(f"⚠️ File {file} is too large, skipping")
log(f"⚠️ File {file} is too large, skipping")
self.skipped += 1

def create_file(self, filename, content):
Expand All @@ -102,10 +98,10 @@ def create_file(self, filename, content):
def scan_files(self, path):
out = []
for i in os.listdir(path):
if not isfile(path + "/" + i): # Item is a folder
if not isfile(path + "/" + i): # Item is a folder
out += self.scan_files(path + "/" + i)
else:
self.log(f"Found file {path + '/' + i}")
log(f"Found file {path + '/' + i}")
out.append(path + "/" + i)
return out

Expand All @@ -120,11 +116,12 @@ def upload_file(self, file):
try:
self.cursor.execute(
"INSERT INTO test value(%s, %s, %s, %s)",
(file, round(os.path.getctime(file)), self.hash_file(file), mysql.connector.Binary(self.convert_to_blob(file)),))
(file, round(os.path.getctime(file)), self.hash_file(file),
mysql.connector.Binary(self.convert_to_blob(file)),))
self.connection.commit()
self.uploaded += 1
except mysql.connector.errors.DataError:
self.log(f"⚠️ File {file} is too large, skipping")
log(f"⚠️ File {file} is too large, skipping")
self.skipped += 1

def hash_file(self, file):
Expand All @@ -140,7 +137,7 @@ def hash_file(self, file):
def do(self):
if not self.disabled:
if not os.path.exists(self.path):
self.log("⚠️ New Folder doesn't exist, creating")
log("⚠️ New Folder doesn't exist, creating")
os.makedirs(self.path)

local_files = self.scan_files(self.path)
Expand All @@ -157,13 +154,13 @@ def do(self):
self.compare_files(i)
else:
# New file in db
self.log(f"New file in DB, downloading {i}")
log(f"New file in DB, downloading {i}")
self.download_file(i)
# Find new files that aren't in the db

for i in list(set(local_files) - set(db_files)):
# New file local
self.log(f"{i} is new to the db and will be uploaded")
log(f"{i} is new to the db and will be uploaded")
self.upload_file(i)
self.report()
print("✅ Sync successful")
Expand All @@ -179,3 +176,7 @@ def close(self):
print("Closing sync connection...")
self.connection.close()


def log(self, *args):
if self.verbose:
print(*args)
7 changes: 0 additions & 7 deletions src/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,6 @@ def show_about_dialogue(*args):
tooltip_text="New Note")
self.pack_start(self.new_note_btn)

# View mode button (Remove - not a priority)
# self.view_mode_btn = Gtk.Button()
# self.view_mode_btn.set_icon_name("org.gnome.gedit-symbolic")
# self.view_mode_btn.set_tooltip_text("Switch to view mode")
# self.view_mode_btn.connect("clicked", change_view_mode)
# self.pack_end(self.view_mode_btn)

# Edit Button
self.edit_btn = Gtk.Button(icon_name="ymuse-edit-symbolic",
visible=False)
Expand Down

0 comments on commit a7fde63

Please sign in to comment.