113 lines
2.4 KiB
Python
Executable File
113 lines
2.4 KiB
Python
Executable File
import click
|
|
from click import Context
|
|
|
|
import SimpleNotesApi
|
|
import utils
|
|
from Config import Config
|
|
from jwtutils import is_expired
|
|
from utils import edit_md
|
|
|
|
api: SimpleNotesApi
|
|
base_url: str
|
|
conf = Config()
|
|
|
|
|
|
@click.group()
|
|
@click.pass_context
|
|
def cli(ctx: Context):
|
|
global base_url
|
|
global api
|
|
|
|
conf.load()
|
|
base_url = conf.base_url
|
|
api = SimpleNotesApi.SimplenotesApi(base_url)
|
|
|
|
if ctx.invoked_subcommand == "login" or ctx.invoked_subcommand == "config":
|
|
return
|
|
|
|
token = conf.token
|
|
if token is None:
|
|
click.secho("Please login", err=True, fg="red")
|
|
exit(1)
|
|
elif is_expired(token):
|
|
click.secho("Login expired, please login again", err=True, fg="red")
|
|
exit(1)
|
|
else:
|
|
api.set_token(token)
|
|
|
|
|
|
@cli.command()
|
|
@click.option("--username", prompt=True)
|
|
@click.option("--password", prompt=True, hide_input=True)
|
|
def login(username: str, password: str):
|
|
token = api.login(username, password)
|
|
if token:
|
|
conf.token = token
|
|
conf.save()
|
|
click.secho(f"Welcome {username}", fg="green")
|
|
else:
|
|
click.echo("Invalid credentials")
|
|
exit(1)
|
|
|
|
|
|
@cli.command()
|
|
@click.option("--url", prompt=True)
|
|
def config(url: str):
|
|
conf.base_url = url
|
|
conf.save()
|
|
|
|
|
|
@cli.command(name="list")
|
|
def list_notes():
|
|
utils.print_notes(api.list_notes())
|
|
|
|
|
|
@cli.command()
|
|
@click.argument("uuid")
|
|
def edit(uuid: str):
|
|
note = api.find_note(uuid)
|
|
if not note:
|
|
click.secho("Note not found", err=True, fg="red")
|
|
exit(1)
|
|
|
|
edited = edit_md(note)
|
|
|
|
if edited == note:
|
|
exit(1)
|
|
|
|
if not api.update_note(uuid, edited):
|
|
click.secho("An error occurred", err=True, fg="red")
|
|
exit(1)
|
|
else:
|
|
utils.print_note_url(uuid, "updated", conf.base_url)
|
|
|
|
|
|
@cli.command()
|
|
def new():
|
|
placeholder = "---\ntitle: ''\ntags: []\n---\n"
|
|
md = edit_md(placeholder)
|
|
if md == placeholder:
|
|
exit(1)
|
|
uuid = api.create_note(md)
|
|
if uuid:
|
|
utils.print_note_url(uuid, "created", conf.base_url)
|
|
else:
|
|
click.secho("An error occurred", err=True, fg="red")
|
|
exit(1)
|
|
|
|
|
|
@cli.command(name="search")
|
|
@click.argument("search", nargs=-1, required=True)
|
|
def search_notes(search: str):
|
|
query = " ".join(search)
|
|
notes = api.search_notes(query)
|
|
|
|
if not notes:
|
|
print("No match")
|
|
else:
|
|
utils.print_notes(notes)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
cli()
|