Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #50

Merged
merged 2 commits into from
Jul 31, 2024
Merged

Dev #50

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Main.sublime-menu
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"caption": "Settings",
"command": "edit_settings",
"args": {
"base_file": "${packages}/Simplenote/Default.sublime-settings",
"base_file": "${packages}/Simplenote/Simplenote.sublime-settings",
"default": "// Simplenote Settings - User\n{\n\t$0\n}\n"
},
},
Expand Down
File renamed without changes.
34 changes: 26 additions & 8 deletions _config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import sys
import typing

from sublime import cache_path, packages_path


# try:
# from dotenv import load_dotenv
Expand All @@ -16,6 +18,7 @@
# else:
# load_dotenv()


__all__ = [
"CONFIG",
]
Expand All @@ -40,9 +43,8 @@ def __init_subclass__(cls, **kwargs):

SIMPLENOTE_PROJECT_NAME: str = "Simplenote"
SIMPLENOTE_PROJECT_VERSION: str = "0.0.1"
SIMPLENOTE_PROJECT_DESCRIPTION: str = "Sublime Text 3/4 plugin for Simplenote."
SIMPLENOTE_PROJECT_DESCRIPTION: str = "Sublime Text 3 & 4 plugin for Simplenote."

SIMPLENOTE_BASE_DIR: str = BASE_DIR
SIMPLENOTE_APP_ID: str = os.getenv("SIMPLENOTE_APP_ID", "chalk-bump-f49")
__SIMPLENOTE_APP_KEY: str = os.getenv("SIMPLENOTE_APP_KEY", "YzhjMmI4NjMzNzE1NGNkYWJjOTg5YjIzZTMwYzZiZjQ=")
# There is no way for us to hide this key, only obfuscate it.
Expand All @@ -53,13 +55,29 @@ def __init_subclass__(cls, **kwargs):
SIMPLENOTE_BUCKET: str = os.getenv("SIMPLENOTE_BUCKET", "note")
SIMPLENOTE_USERNAME: str = os.getenv("SIMPLENOTE_USERNAME", "")
SIMPLENOTE_PASSWORD: str = os.getenv("SIMPLENOTE_PASSWORD", "")
SIMPLENOTE_SETTINGS_FILE: str = "Default.sublime-settings"
SIMPLENOTE_TOKEN_FILE: str = os.getenv("SIMPLENOTE_TOKEN_FILE", "simplenote_token.pkl")
SIMPLENOTE_STARTED: bool = False
SIMPLENOTE_RELOAD_CALLS: int = -1
SIMPLENOTE_NOTE_FETCH_LENGTH: int = 1
SIMPLENOTE_NOTE_CACHE_FILE: str = "note_cache.pkl"
SIMPLENOTE_DEFAULT_NOTE_TITLE: str = "untitled"
SIMPLENOTE_SETTINGS_FILE: str = "Simplenote.sublime-settings"

SIMPLENOTE_PACKAGE_DIR = os.path.join(packages_path(), SIMPLENOTE_PROJECT_NAME)
os.makedirs(SIMPLENOTE_PACKAGE_DIR, exist_ok=True)

SUBLIME_USER_DIR = os.path.join(packages_path(), "User")
SIMPLENOTE_SETTINGS_FILE_PATH = os.path.join(SUBLIME_USER_DIR, SIMPLENOTE_SETTINGS_FILE)
if not os.path.exists(SIMPLENOTE_SETTINGS_FILE_PATH):
import shutil

default_settings = os.path.join(os.path.dirname(__file__), SIMPLENOTE_SETTINGS_FILE)
shutil.copy(default_settings, SIMPLENOTE_SETTINGS_FILE_PATH)

SIMPLENOTE_CACHE_DIR = os.path.join(cache_path(), SIMPLENOTE_PROJECT_NAME)
os.makedirs(SIMPLENOTE_CACHE_DIR, exist_ok=True)
SIMPLENOTE_TOKEN_FILE_PATH = os.path.join(SIMPLENOTE_CACHE_DIR, "token.json")
SIMPLENOTE_NOTE_CACHE_FILE_PATH = os.path.join(SIMPLENOTE_CACHE_DIR, "note_cache.pkl")
SIMPLENOTE_NOTES_DIR = os.path.join(SIMPLENOTE_CACHE_DIR, "notes")
os.makedirs(SIMPLENOTE_NOTES_DIR, exist_ok=True)

# SIMPLENOTE_STARTED: bool = False
# SIMPLENOTE_RELOAD_CALLS: int = -1


class Development(_BaseConfig):
Expand Down
10 changes: 4 additions & 6 deletions api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
import functools
import json
import logging
import os
import time
from typing import Any, Dict, Optional
from urllib.parse import urlencode
from uuid import uuid4

from ._config import CONFIG
from .utils.patterns.singleton.base import Singleton
from .utils.request import Response, request

Expand All @@ -21,12 +21,10 @@

__all__ = ["Simplenote"]

SIMPLENOTE_BASE_DIR = os.path.abspath(os.path.dirname(__file__))

SIMPLENOTE_APP_ID: str = "chalk-bump-f49"
SIMPLENOTE_APP_KEY: str = base64.b64decode("YzhjMmI4NjMzNzE1NGNkYWJjOTg5YjIzZTMwYzZiZjQ=").decode("utf-8")
SIMPLENOTE_BUCKET: str = "note"
_SIMPLENOTE_TOKEN_FILE = "token.json"
SIMPLENOTE_TOKEN_FILE = os.path.join(SIMPLENOTE_BASE_DIR, _SIMPLENOTE_TOKEN_FILE)


class URL:
Expand Down Expand Up @@ -144,7 +142,7 @@ def token(self):
"""
if not self._token:
try:
with open(SIMPLENOTE_TOKEN_FILE, "r") as fh:
with open(CONFIG.SIMPLENOTE_TOKEN_FILE_PATH, "r") as fh:
_token = json.load(fh)
token = _token.get(self.username)
if not token:
Expand All @@ -153,7 +151,7 @@ def token(self):
except Exception as err:
logger.info("Do not have token cache for %s, requesting new one. Error: %s" % (self.username, err))
self._token = self.authenticate(self.username, self.password)
with open(SIMPLENOTE_TOKEN_FILE, "w+") as fh:
with open(CONFIG.SIMPLENOTE_TOKEN_FILE_PATH, "w+") as fh:
try:
_token = json.load(fh)
except Exception as err:
Expand Down
18 changes: 0 additions & 18 deletions gui.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import logging
import os
from typing import Optional

import sublime
Expand All @@ -9,30 +8,13 @@


__all__ = [
"SIMPLENOTE_PACKAGE_DIR",
"SIMPLENOTE_SETTINGS_FILE",
"SIMPLENOTE_BASE_DIR",
"show_message",
"remove_status",
"get_view_window",
"open_view",
"close_view",
]

SIMPLENOTE_PROJECT_NAME = "Simplenote"
SIMPLENOTE_SETTINGS_FILE = "Default.sublime-settings"

SIMPLENOTE_PACKAGE_DIR = sublime.packages_path()
SIMPLENOTE_BASE_DIR = os.path.join(SIMPLENOTE_PACKAGE_DIR, "Simplenote")

SIMPLENOTE_CACHE_DIR = os.path.join(sublime.cache_path(), SIMPLENOTE_PROJECT_NAME)
os.makedirs(SIMPLENOTE_CACHE_DIR, exist_ok=True)

SIMPLENOTE_NOTES_DIR = os.path.join(SIMPLENOTE_CACHE_DIR, "notes")
os.makedirs(SIMPLENOTE_NOTES_DIR, exist_ok=True)

SIMPLENOTE_SETTINGS_FILE_PATH = os.path.join(SIMPLENOTE_BASE_DIR, SIMPLENOTE_SETTINGS_FILE)


# def init_settings(reload_if_needed: Optional(Callable) = None):
# global SETTINGS
Expand Down
31 changes: 17 additions & 14 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@

import sublime

from ._config import CONFIG
from .api import Simplenote
from .gui import SIMPLENOTE_NOTES_DIR, SIMPLENOTE_SETTINGS_FILE
from .utils.decorator import class_property
from .utils.tree.redblacktree import rbtree as RedBlackTree

Expand All @@ -22,9 +22,6 @@
logger = logging.getLogger()


SIMPLENOTE_DEFAULT_NOTE_TITLE = "untitled"


# Take out invalid characters from title and use that as base for the name
VALID_CHARS = "-_.() %s%s" % (string.ascii_letters, string.digits)

Expand Down Expand Up @@ -144,13 +141,18 @@ def __init__(self, id: str = "", v: int = 0, d: Dict[str, Any] = {}, **kwargs):

@class_property
def API(cls) -> Simplenote:
settings = sublime.load_settings(SIMPLENOTE_SETTINGS_FILE)
settings = sublime.load_settings(CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH)
username = settings.get("username")
password = settings.get("password")
if not all([username, password]):
raise Exception("Missing username or password")
raise Exception(
"Missing username or password, Please check settings file: %s" % CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH
)
if not isinstance(username, str) or not isinstance(password, str):
raise Exception("username and password must be strings")
raise Exception(
"username and password must be strings, Please check settings file: %s"
% CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH
)
return Simplenote(username, password)

@classmethod
Expand Down Expand Up @@ -225,15 +227,15 @@ def _title(self):
try:
content = self._content
except Exception:
return SIMPLENOTE_DEFAULT_NOTE_TITLE
return CONFIG.SIMPLENOTE_DEFAULT_NOTE_TITLE
return self.get_title(content)

@property
def title(self):
try:
content = self.d.content
except Exception:
return SIMPLENOTE_DEFAULT_NOTE_TITLE
return CONFIG.SIMPLENOTE_DEFAULT_NOTE_TITLE
return self.get_title(content)

@staticmethod
Expand All @@ -242,7 +244,7 @@ def get_title(content: str) -> str:
if index > -1:
title = content[:index]
else:
title = content or SIMPLENOTE_DEFAULT_NOTE_TITLE
title = content or CONFIG.SIMPLENOTE_DEFAULT_NOTE_TITLE
return title

@property
Expand All @@ -256,11 +258,12 @@ def filename(self) -> str:

@staticmethod
def get_filename(id: str, title: str) -> str:
settings = sublime.load_settings(SIMPLENOTE_SETTINGS_FILE)
settings = sublime.load_settings(CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH)
title_extension_map: List[Dict[str, str]] = settings.get("title_extension_map")
if not isinstance(title_extension_map, list):
logger.info(
"`title_extension_map` must be a list. Please check settings file: %s." % SIMPLENOTE_SETTINGS_FILE
"`title_extension_map` must be a list. Please check settings file: %s."
% CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH
)
base = "".join(c for c in title if c in VALID_CHARS)
# Determine extension based on title
Expand All @@ -283,7 +286,7 @@ def filepath(self) -> str:

@staticmethod
def get_filepath(filename: str):
return os.path.join(SIMPLENOTE_NOTES_DIR, filename)
return os.path.join(CONFIG.SIMPLENOTE_NOTES_DIR, filename)

@staticmethod
def write_content_to_path(filepath: str, content: str = ""):
Expand Down Expand Up @@ -324,7 +327,7 @@ def close(self):
def get_note_from_filepath(view_absolute_filepath: str):
assert isinstance(view_absolute_filepath, str), "view_absolute_filepath must be a string"
view_note_dir, view_note_filename = os.path.split(view_absolute_filepath)
if view_note_dir != SIMPLENOTE_NOTES_DIR:
if view_note_dir != CONFIG.SIMPLENOTE_NOTES_DIR:
return
pattern = re.compile(r"\((.*?)\)")
for note in Note.mapper_id_note.values():
Expand Down
11 changes: 6 additions & 5 deletions operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

import sublime

from .gui import SIMPLENOTE_SETTINGS_FILE_PATH, _show_message, open_view, remove_status
from ._config import CONFIG
from .gui import _show_message, open_view, remove_status
from .models import Note
from .utils.patterns.singleton.base import Singleton

Expand Down Expand Up @@ -67,7 +68,7 @@ def run(self):
except Exception as err:
logger.exception(err)
sublime.message_dialog(str(err))
open_view(SIMPLENOTE_SETTINGS_FILE_PATH)
open_view(CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH)
self.result = err


Expand All @@ -81,7 +82,7 @@ def run(self):
except Exception as err:
logger.exception(err)
sublime.message_dialog(str(err))
open_view(SIMPLENOTE_SETTINGS_FILE_PATH)
open_view(CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH)
self.result = err


Expand All @@ -99,7 +100,7 @@ def run(self):
except Exception as err:
logger.exception(err)
sublime.message_dialog(str(err))
open_view(SIMPLENOTE_SETTINGS_FILE_PATH)
open_view(CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH)
self.result = err


Expand All @@ -116,7 +117,7 @@ def run(self):
except Exception as err:
logger.exception(err)
sublime.message_dialog(str(err))
open_view(SIMPLENOTE_SETTINGS_FILE_PATH)
open_view(CONFIG.SIMPLENOTE_SETTINGS_FILE_PATH)
self.result = err


Expand Down
24 changes: 11 additions & 13 deletions simplenote.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
# https://www.sublimetext.com/docs/api_reference.html
import sublime

from .gui import SIMPLENOTE_CACHE_DIR, close_view, open_view
from .models import SIMPLENOTE_NOTES_DIR, Note
from ._config import CONFIG
from .gui import close_view, open_view
from .models import Note
from .utils.patterns.singleton.base import Singleton


Expand All @@ -25,9 +26,6 @@
logger = logging.getLogger()


SIMPLENOTE_NOTE_CACHE_FILE = os.path.join(SIMPLENOTE_CACHE_DIR, "note_cache.pkl")


class _BaseManager(Singleton):
pass

Expand Down Expand Up @@ -56,14 +54,14 @@ def objects(self, value: List[Note]):
self._objects = value

@staticmethod
def _save_objects(SIMPLENOTE_NOTE_CACHE_FILE: str, objects: List[Note]):
with open(SIMPLENOTE_NOTE_CACHE_FILE, "w+b") as cache_file:
def _save_objects(SIMPLENOTE_NOTE_CACHE_FILE_PATH: str, objects: List[Note]):
with open(SIMPLENOTE_NOTE_CACHE_FILE_PATH, "w+b") as cache_file:
pickle.dump(objects, cache_file)

@classmethod
def save_objects(cls):
return
cls._save_objects(SIMPLENOTE_NOTE_CACHE_FILE, cls._objects)
cls._save_objects(CONFIG.SIMPLENOTE_NOTE_CACHE_FILE_PATH, cls._objects)

@staticmethod
def dict_to_model(note: Dict[str, Any]) -> Note:
Expand All @@ -85,21 +83,21 @@ def dict_to_model(note: Dict[str, Any]) -> Note:

def load_notes():
try:
with open(SIMPLENOTE_NOTE_CACHE_FILE, "rb") as cache_file:
with open(CONFIG.SIMPLENOTE_NOTE_CACHE_FILE_PATH, "rb") as cache_file:
Note.mapper_id_note = pickle.load(cache_file, encoding="utf-8")
except (EOFError, IOError, FileNotFoundError) as err:
logger.exception(err)
with open(SIMPLENOTE_NOTE_CACHE_FILE, "w+b") as cache_file:
with open(CONFIG.SIMPLENOTE_NOTE_CACHE_FILE_PATH, "w+b") as cache_file:
pickle.dump(Note.mapper_id_note, cache_file)
logger.debug((f"Created new objects cache file: {SIMPLENOTE_NOTE_CACHE_FILE}"))
logger.debug((f"Created new objects cache file: {CONFIG.SIMPLENOTE_NOTE_CACHE_FILE_PATH}"))


def clear_orphaned_filepaths(list__filename: List[str] = []):
if not list__filename:
list__filename = [note.filename for note in Note.mapper_id_note.values()]
for filename in os.listdir(SIMPLENOTE_NOTES_DIR):
for filename in os.listdir(CONFIG.SIMPLENOTE_NOTES_DIR):
if filename not in list__filename:
os.remove(os.path.join(SIMPLENOTE_NOTES_DIR, filename))
os.remove(os.path.join(CONFIG.SIMPLENOTE_NOTES_DIR, filename))


def sort_notes(a_note: Note, b_note: Note):
Expand Down
4 changes: 2 additions & 2 deletions simplenote.sublime-commands
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
"caption": "Preferences: Simplenote Settings",
"command": "edit_settings",
"args": {
"base_file": "${packages}/Simplenote/Default.sublime-settings",
"default": "// Settings in here override those in \"Simplenote/Default.sublime-settings\",\n// and are overridden in turn by syntax-specific settings.\n{\n\t$0\n}\n"
"base_file": "${packages}/Simplenote/Simplenote.sublime-settings",
"default": "// Settings in here override those in \"Simplenote/Simplenote.sublime-settings\",\n// and are overridden in turn by syntax-specific settings.\n{\n\t$0\n}\n"
}
},
{
Expand Down
Loading