You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
NotePostCLI/notepostcli/notepost.py

204 lines
4.7 KiB
Python

#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
import os
try:
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
except:
pass
import tempfile
import requests
import re
import api
from config import *
from termcolors import *
from getpass import getpass
editor = "/usr/bin/editor"
notes = {}
def firstsetup(url="", username=""):
# Get URL
while True:
if url != "":
url = input("Server URL (" + url + "): ") or url
else:
url = input("Server URL: ")
if re.compile("^(https?|ftp)://[^\s/$.?#].[^\s]*$").match(url):
break
else:
print("That doesn't look right, try again.")
# Get username
while True:
if username != "":
username = input("Username (" + username + "): ") or username
else:
username = input("Username: ")
if username != "":
break
# Get password
while True:
password = getpass("Password: ")
if password != "":
break
try:
r = requests.post(url + "/api/ping", auth=(username, password))
except:
print("Could not connect to the server. Try again.")
firstsetup()
return
if r.status_code == 401:
print("Login incorrect, try again.")
firstsetup(url)
return
try:
resp = r.json()
if resp["status"] == "ERROR":
print(resp["msg"])
firstsetup(url, username)
return
config["url"] = url
config["username"] = username
config["password"] = password
saveconfig()
return
except ValueError:
print("Login incorrect, try again.")
firstsetup(url, username)
return
def loadnotes():
global notes
notes = api.do("getnotes")["notes"]
def savenote(note):
api.do("savenote", {
"id": note["noteid"],
"text": note["content"]
})
def editnote(note):
global editor
content = note["content"]
f = tempfile.NamedTemporaryFile(mode='w+')
f.write(content)
f.flush()
command = editor + " " + f.name
status = os.system(command)
f.seek(0, 0)
text = f.read()
f.close()
assert not os.path.exists(f.name)
note["content"] = text
clearscreen()
print("Saving...")
savenote(note)
print("Note saved!")
def editmenu():
global notes
rows, columns = os.popen('stty size', 'r').read().split()
linelength = int(columns) - 10
clearscreen()
loadnotes()
i = 1
notelist = {}
for note in notes:
notelist[str(i)] = note
print(chr(27) + "[0m", end='')
print("\n\nNote #" + str(i) + ":")
setbghexcolor(note["color"])
setfgbybghex(note["color"])
linecount = 0
for line in note["content"].splitlines():
if linecount > 5:
print("\n(" + str(len(note["content"].splitlines())) + " more lines" + ")", end='')
break
print("\n " + line[0:linelength].ljust(linelength), end='')
if len(line) > linelength:
print("...", end='')
linecount += 1
i += 1
resetcolor()
print("\n======================")
noteid = input("Note to edit (M for main menu): ")
if noteid.upper() == "M":
clearscreen()
return
try:
editnote(notelist[noteid])
except KeyError:
print("Invalid selection.")
def newnote():
global editor
print()
f = tempfile.NamedTemporaryFile(mode='w+')
f.write("")
f.flush()
command = editor + " " + f.name
status = os.system(command)
f.seek(0, 0)
text = f.read()
f.close()
assert not os.path.exists(f.name)
if text == "":
clearscreen()
print("Nothing to do.")
return
print("Saving...")
api.do("savenote", {
"text": text
})
print("Note created!")
def mainmenu():
print("\n======================")
print("Main Menu")
print("======================")
print("E. View and edit notes")
print("C. Create a new note")
print("Q. Exit")
option = input("Choose an option: ").upper()
clearscreen()
if option == "E":
editmenu()
elif option == "C":
newnote()
elif option == "Q":
exit(0)
else:
print("Unrecognized selection, try again.")
def main():
print("NotePostCLI v0.1")
if not checkconfig():
print("No valid settings file found, running setup wizard.")
firstsetup()
else:
loadconfig()
while True:
mainmenu()
if __name__ == "__main__":
main()