NotePostCLI/notepostcli/notepost.py

206 lines
4.8 KiB
Python
Raw Normal View History

2018-12-27 16:39:41 -07:00
#!/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/.
2018-12-28 17:30:32 -07:00
import sys
import os
try:
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
except:
pass
2018-12-28 02:06:28 -07:00
import tempfile
2018-12-27 16:39:41 -07:00
import requests
2019-01-15 16:25:51 -07:00
import re
2018-12-28 01:56:10 -07:00
import api
from config import *
2018-12-28 01:56:10 -07:00
from termcolors import *
2018-12-27 16:39:41 -07:00
from getpass import getpass
2018-12-28 01:56:10 -07:00
editor = "/usr/bin/editor"
notes = {}
def firstsetup(url="", username=""):
# Get URL
2018-12-27 16:39:41 -07:00
while True:
if url != "":
2019-01-15 16:25:51 -07:00
url = input("Server URL (" + url + "): ") or url
else:
2019-01-15 16:25:51 -07:00
url = input("Server URL: ")
if re.compile("^(https?|ftp)://[^\s/$.?#].[^\s]*$").match(url):
2018-12-27 16:39:41 -07:00
break
else:
2019-01-15 16:25:51 -07:00
print("That doesn't look right, try again.")
# Get username
2018-12-27 16:39:41 -07:00
while True:
if username != "":
2019-01-15 16:25:51 -07:00
username = input("Username (" + username + "): ") or username
else:
2019-01-15 16:25:51 -07:00
username = input("Username: ")
2018-12-27 16:39:41 -07:00
if username != "":
break
# Get password
2018-12-27 16:39:41 -07:00
while True:
2019-01-15 16:25:51 -07:00
password = getpass("Password: ")
2018-12-27 16:39:41 -07:00
if password != "":
break
try:
r = requests.post(url + "/api/ping", auth=(username, password))
except:
2019-01-15 16:25:51 -07:00
print("Could not connect to the server. Try again.")
firstsetup()
return
if r.status_code == 401:
2019-01-15 16:25:51 -07:00
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:
2019-01-15 16:25:51 -07:00
print("Login incorrect, try again.")
firstsetup(url, username)
return
2018-12-27 16:39:41 -07:00
2018-12-28 01:56:10 -07:00
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()
2019-01-15 16:25:51 -07:00
print("Saving...")
2018-12-28 01:56:10 -07:00
savenote(note)
2019-01-15 16:25:51 -07:00
print("Note saved!")
2018-12-28 01:56:10 -07:00
def editmenu():
global notes
2019-01-15 16:25:51 -07:00
rows, columns = os.popen('stty size', 'r').read().split()
2019-01-15 16:32:32 -07:00
linelength = int(columns) - 5
2018-12-28 01:56:10 -07:00
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
2019-01-15 16:32:32 -07:00
print("\n " + line[0:linelength].ljust(linelength), end='')
2019-01-15 16:25:51 -07:00
if len(line) > linelength:
2018-12-28 01:56:10 -07:00
print("...", end='')
2019-01-15 16:32:32 -07:00
else:
print(" ", end='')
2018-12-28 01:56:10 -07:00
linecount += 1
i += 1
resetcolor()
print("\n======================")
2019-01-15 16:25:51 -07:00
noteid = input("Note to edit (M for main menu): ")
2018-12-28 01:56:10 -07:00
if noteid.upper() == "M":
clearscreen()
return
try:
editnote(notelist[noteid])
except KeyError:
2019-01-15 16:25:51 -07:00
print("Invalid selection.")
2018-12-28 01:56:10 -07:00
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()
2019-01-15 16:25:51 -07:00
print("Nothing to do.")
2018-12-28 01:56:10 -07:00
return
2019-01-15 16:25:51 -07:00
print("Saving...")
2018-12-28 01:56:10 -07:00
api.do("savenote", {
"text": text
})
2019-01-15 16:25:51 -07:00
print("Note created!")
2018-12-28 01:56:10 -07:00
def mainmenu():
print("\n======================")
2019-01-15 16:25:51 -07:00
print("Main Menu")
2018-12-28 01:56:10 -07:00
print("======================")
2019-01-15 16:25:51 -07:00
print("E. View and edit notes")
print("C. Create a new note")
print("Q. Exit")
option = input("Choose an option: ").upper()
2018-12-28 01:56:10 -07:00
clearscreen()
if option == "E":
editmenu()
elif option == "C":
newnote()
elif option == "Q":
exit(0)
else:
2019-01-15 16:25:51 -07:00
print("Unrecognized selection, try again.")
2018-12-28 01:56:10 -07:00
2018-12-27 16:39:41 -07:00
def main():
print("NotePostCLI v0.1")
2018-12-27 16:39:41 -07:00
if not checkconfig():
2019-01-15 16:25:51 -07:00
print("No valid settings file found, running setup wizard.")
2018-12-27 16:39:41 -07:00
firstsetup()
else:
loadconfig()
2018-12-28 01:56:10 -07:00
while True:
mainmenu()
2018-12-27 16:39:41 -07:00
if __name__ == "__main__":
main()