Browse files

pre-release

  • Loading branch information...
1 parent 8926c00 commit 6ff24a6b1372b1afac5cfce35d8513d0d7804d88 @stepler stepler committed Jul 2, 2012
Showing with 131 additions and 109 deletions.
  1. +41 −42 argparser.py
  2. +20 −3 config.py
  3. +4 −4 editor.py
  4. +47 −41 geeknote.py
  5. +1 −7 oauth.py
  6. +17 −9 out.py
  7. +1 −3 tools.py
View
83 argparser.py
@@ -8,108 +8,107 @@
COMMANDS_DICT = {
# User
"user": {
- "help": "Create note",
+ "help": "Show information about active user.",
"flags": {
- "--full": {"help": "Add tag to note", "value": True, "default": False},
+ "--full": {"help": "Show full information.", "value": True, "default": False},
}
},
"login": {
- "help": "Create note",
+ "help": "Authorize in Evernote.",
},
"logout": {
- "help": "Create note",
+ "help": "Logout from Evernote.",
"flags": {
- "--force": {"help": "Add tag to note", "value": True, "default": False},
+ "--force": {"help": "Don't ask about logging out.", "value": True, "default": False},
}
},
"settings": {
- "help": "Create note",
+ "help": "Show and edit current settings.",
"arguments": {
- "--editor": {"help": "Set system editor", "emptyValue": '#GET#'},
+ "--editor": {"help": "Set the editor, which use to edit and create notes.", "emptyValue": '#GET#'},
}
},
# Notes
"create": {
- "help": "Create note",
+ "help": "Create note in evernote.",
"arguments": {
- "--title": {"help": "Set note title", "required": True},
- "--content": {"help": "Set note content", "required": True},
- "--tags": {"help": "Add tag to note"},
- "--notebook": {"help": "Add location marker to note"}
+ "--title": {"help": "The note title.", "required": True},
+ "--content": {"help": "The note content.", "required": True},
+ "--tags": {"help": "One tag or the list of tags which will be added to the note."},
+ "--notebook": {"help": "Set the notebook where to save note."}
}
},
"edit": {
- "help": "Create note",
+ "help": "Edit note in Evernote.",
"firstArg": "--note",
"arguments": {
- "--note": {"help": "Set note title"},
- "--title": {"help": "Set note title"},
- "--content": {"help": "Set note content"},
- "--tags": {"help": "Add tag to note"},
- "--notebook": {"help": "Add location marker to note"}
+ "--note": {"help": "The name or ID from the previous search of a note to edit."},
+ "--title": {"help": "Set new title of the note."},
+ "--content": {"help": "Set new content of the note."},
+ "--tags": {"help": "Set new list o tags for the note."},
+ "--notebook": {"help": "Assign new notebook for the note."}
}
},
"remove": {
- "help": "Create note",
+ "help": "Remove note from Evernote.",
"firstArg": "--note",
"arguments": {
- "--note": {"help": "Set note title"},
+ "--note": {"help": "The name or ID from the previous search of a note to remove."},
},
"flags": {
- "--force": {"help": "Add tag to note", "value": True, "default": False},
+ "--force": {"help": "Don't ask about removing.", "value": True, "default": False},
}
},
"show": {
- "help": "Create note",
+ "help": "Output note in the terminal.",
"firstArg": "--note",
"arguments": {
- "--note": {"help": "Set note title"},
+ "--note": {"help": "The name or ID from the previous search of a note to show."},
}
},
"find": {
- "help": "Create note",
+ "help": "Search notes in Evernote.",
"firstArg": "--search",
"arguments": {
- "--search": {"help": "Add tag to note", "emptyValue": "*"},
- "--tags": {"help": "Add tag to note"},
- "--notebooks": {"help": "Add location marker to note"},
- "--date": {"help": "Add location marker to note"},
- "--count": {"help": "Add location marker to note", "type": int},
+ "--search": {"help": "Text to search.", "emptyValue": "*"},
+ "--tags": {"help": "Notes with which tag/tags to search."},
+ "--notebooks": {"help": "In which notebook search the note."},
+ "--date": {"help": "Set date in format dd.mm.yyyy or date range dd.mm.yyyy-dd.mm.yyyy."},
+ "--count": {"help": "How many notes show in the result list.", "type": int},
},
"flags": {
- "--exact-entry": {"help": "Add tag to note", "value": True, "default": False},
- "--content-search": {"help": "Add tag to note", "value": True, "default": False},
- "--url-only": {"help": "Add tag to note", "value": True, "default": False},
+ "--exact-entry": {"help": "Search for exact entry of the request.", "value": True, "default": False},
+ "--content-search": {"help": "Search by content, not by title.", "value": True, "default": False},
}
},
# Notebooks
"notebook-list": {
- "help": "Create note",
+ "help": "Show the list of existing notebooks in your Evernote.",
},
"notebook-create": {
- "help": "Create note",
+ "help": "Create new notebook.",
"arguments": {
- "--title": {"help": "Set note title"},
+ "--title": {"help": "Set the title of new notebook."},
}
},
"notebook-edit": {
- "help": "Create note",
+ "help": "Edit/rename notebook.",
"firstArg": "--notebook",
"arguments": {
- "--notebook": {"help": "Set note title"},
- "--title": {"help": "Set note title"},
+ "--notebook": {"help": "The name of a notebook to rename."},
+ "--title": {"help": "Set the new name of notebook."},
}
},
"notebook-remove": {
- "help": "Create note",
+ "help": "Remove notebook.",
"firstArg": "--notebook",
"arguments": {
- "--notebook": {"help": "Set note title"},
+ "--notebook": {"help": "The name of a notebook to remove."},
},
"flags": {
- "--force": {"help": "Add tag to note", "value": True, "default": False},
+ "--force": {"help": "Don't ask about removing.", "value": True, "default": False},
}
},
}
@@ -303,7 +302,7 @@ def printErrorReqArgument(self, errorArg):
def printErrorArgument(self, errorArg, errorVal=None):
if errorVal is None:
- out.printLine('абвUnexpected argument "%s" for command "%s"' % (errorArg, self.CMD))
+ out.printLine('Unexpected argument "%s" for command "%s"' % (errorArg, self.CMD))
else:
out.printLine('Unexpected value "%s" for argument "%s"' % (errorVal, errorArg))
self.printHelp()
View
23 config.py
@@ -4,16 +4,22 @@
# Evernote config
# !!! DO NOT EDIT !!! >>>
+USER_BASE_URL = "www.evernote.com"
+USER_STORE_URI = "https://www.evernote.com/edam/user"
CONSUMER_KEY = "skaizer-1250"
CONSUMER_SECRET = "ed0fcc0c97c032a5"
+USER_BASE_URL_SANDBOX = "sandbox.evernote.com"
+USER_STORE_URI_SANDBOX = "https://sandbox.evernote.com/edam/user"
CONSUMER_KEY_SANDBOX = "skaizer-1250"
CONSUMER_SECRET_SANDBOX = "ed0fcc0c97c032a5"
# !!! DO NOT EDIT !!! <<<
-# Application path
-APP_DIR = os.path.join(os.getenv("USERPROFILE") or os.getenv("HOME"), ".geeknote")
+IS_IN_TERMINAL = sys.stdin.isatty()
+IS_OUT_TERMINAL = sys.stdout.isatty()
+# Application path
+APP_DIR = os.path.join(os.getenv("USERPROFILE") or os.getenv("HOME"), ".geeknote")
ERROR_LOG = os.path.join(APP_DIR, "error.log")
# Set default system editor
@@ -24,10 +30,21 @@
DEV_MODE = True
DEBUG = False
+# Url view the note
+NOTE_URL = "https://%domain%/Home.action?#n=%s"
+
# validate config
try:
if not os.path.exists(APP_DIR):
os.mkdir(APP_DIR)
except Exception, e:
sys.stdout.write("Can not create application dirictory : %s" % APP_DIR)
- exit()
+ exit()
+
+if DEV_MODE:
+ USER_STORE_URI = USER_STORE_URI_SANDBOX
+ CONSUMER_KEY = CONSUMER_KEY_SANDBOX
+ CONSUMER_SECRET = CONSUMER_SECRET_SANDBOX
+ USER_BASE_URL = USER_BASE_URL_SANDBOX
+
+NOTE_URL = NOTE_URL.replace('%domain%', USER_BASE_URL)
View
8 editor.py
@@ -38,11 +38,11 @@ def textToENML(content):
contentHTML = markdown.markdown(content).encode("utf-8")
# remove all new-lines characters in html
contentHTML = re.sub(r'\n', r'', contentHTML)
+ return wrapENML(contentHTML)
except:
- out.failureMessage("Error. Content must be an UTF-8 encode.")
- return None
-
- return wrapENML(contentHTML)
+ logging.error("Error while parsing text to html. Content must be an UTF-8 encode.")
+ out.failureMessage("Error while parsing text to html. Content must be an UTF-8 encode.")
+ return tools.exit()
def edit(content=None):
"""
View
88 geeknote.py
@@ -2,6 +2,8 @@
# -*- coding: utf-8 -*-
import os, sys
+import traceback
+
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.append( os.path.join(PROJECT_ROOT, 'lib') )
@@ -11,6 +13,8 @@
import binascii
import time
from datetime import datetime
+from urlparse import urlparse
+import re
import lib.thrift.protocol.TBinaryProtocol as TBinaryProtocol
import lib.thrift.transport.THttpClient as THttpClient
import lib.evernote.edam.userstore.UserStore as UserStore
@@ -25,7 +29,9 @@
import out
from argparser import argparser
+
from oauth import GeekNoteAuth
+
from storage import Storage
import editor
import tools
@@ -41,9 +47,9 @@ def wrapper(*args, **kwargs):
class GeekNote(object):
+ userStoreUri = config.USER_STORE_URI
consumerKey = config.CONSUMER_KEY
consumerSecret = config.CONSUMER_SECRET
- userStoreUri = "https://evernote.com/edam/user"
authToken = None
userStore = None
noteStore = None
@@ -54,11 +60,6 @@ def __init__(self, skipInitConnection=False):
if skipInitConnection:
self.skipInitConnection = True
- if config.DEV_MODE:
- self.userStoreUri = "https://sandbox.evernote.com/edam/user"
- self.consumerKey = config.CONSUMER_KEY_SANDBOX
- self.consumerSecret = config.CONSUMER_SECRET_SANDBOX
-
self.getStorage()
if self.skipInitConnection is True:
@@ -310,7 +311,7 @@ class User(GeekNoteConnector):
@GeekNoneDBConnectOnly
def user(self, full=None):
if not self.getEvernote().checkAuth():
- out.failureMessage("You not logged in")
+ out.failureMessage("You not logged in.")
return tools.exit()
if full:
@@ -322,29 +323,29 @@ def user(self, full=None):
@GeekNoneDBConnectOnly
def login(self):
if self.getEvernote().checkAuth():
- out.successMessage("You already logged in")
+ out.successMessage("You have already logged in.")
return tools.exit()
if self.getEvernote().auth():
- out.successMessage("You successfully logged in")
+ out.successMessage("You have successfully logged in.")
else:
- out.failureMessage("Login error")
+ out.failureMessage("Login error.")
return tools.exit()
@GeekNoneDBConnectOnly
def logout(self, force=None):
if not self.getEvernote().checkAuth():
- out.successMessage("You already logged out")
+ out.successMessage("You have already logged out.")
return tools.exit()
- if not force and not out.confirm('Are you sure you want logout?'):
+ if not force and not out.confirm('Are you sure you want to logout?'):
return tools.exit()
result = self.getEvernote().removeUser()
if result:
- out.successMessage("Logout successful")
+ out.successMessage("You have successfully logged out.")
else:
- out.failureMessage("Logout error")
+ out.failureMessage("Logout error.")
return tools.exit()
@GeekNoneDBConnectOnly
@@ -357,7 +358,7 @@ def settings(self, editor=None):
out.successMessage("Current editor is: %s" % editor)
else:
self.getStorage().setUserprop('editor', editor)
- out.successMessage("Editor successfully saved")
+ out.successMessage("Changes have been saved.")
class Notebooks(GeekNoteConnector):
""" Work with auth Notebooks """
@@ -372,9 +373,9 @@ def create(self, title):
result = self.getEvernote().createNotebook(name=title)
if result:
- out.successMessage("Notebook successfully created")
+ out.successMessage("Notebook has been successfully created.")
else:
- out.failureMessage("Error while creating the notebook")
+ out.failureMessage("Error while the process of creating the notebook.")
return tools.exit()
return result
@@ -387,9 +388,9 @@ def edit(self, notebook, title):
result = self.getEvernote().updateNotebook(guid=notebook.guid, name=title)
if result:
- out.successMessage("Notebook successfully updated")
+ out.successMessage("Notebook has been successfully updated.")
else:
- out.failureMessage("Error while updating the notebook")
+ out.failureMessage("Error while the updating the notebook.")
return tools.exit()
def remove(self, notebook, force=None):
@@ -403,9 +404,9 @@ def remove(self, notebook, force=None):
result = self.getEvernote().deleteNotebook(guid=notebook.guid)
if result:
- out.successMessage("Notebook successfully removed")
+ out.successMessage("Notebook has been successfully removed.")
else:
- out.failureMessage("Error while removing the notebook")
+ out.failureMessage("Error while removing the notebook.")
def _searchNotebook(self, notebook):
@@ -451,9 +452,9 @@ def create(self, title, content, tags=None, notebook=None):
result = self.getEvernote().createNote(**inputData)
if result:
- out.successMessage("Note successfully created")
+ out.successMessage("Note has been successfully created.")
else:
- out.failureMessage("Error while creating the note")
+ out.failureMessage("Error while creating the note.")
def edit(self, note, title=None, content=None, tags=None, notebook=None):
@@ -466,9 +467,9 @@ def edit(self, note, title=None, content=None, tags=None, notebook=None):
result = self.getEvernote().updateNote(guid=note.guid, **inputData)
if result:
- out.successMessage("Note successfully saved")
+ out.successMessage("Note has been successfully saved.")
else:
- out.failureMessage("Error while saving the note")
+ out.failureMessage("Error while saving the note.")
def remove(self, note, force=None):
@@ -482,16 +483,16 @@ def remove(self, note, force=None):
result = self.getEvernote().deleteNote(note.guid)
if result:
- out.successMessage("Note successful deleted")
+ out.successMessage("Note has been successful deleted.")
else:
- out.failureMessage("Error while deleting the note")
+ out.failureMessage("Error while deleting the note.")
def show(self, note):
self.connectToEvertone()
note = self._searchNote(note)
-
+
out.preloader.setMessage("Loading note...")
self.getEvernote().loadNoteContent(note)
@@ -523,15 +524,11 @@ def _parceInput(self, title=None, content=None, tags=None, notebook=None, note=N
content = editor.edit()
elif isinstance(content, str) and os.path.isfile(content):
- logging.debug("Load content file")
+ logging.debug("Load content from the file")
content = open(content, "r").read()
- content = editor.ENMLtoText(content)
logging.debug("Convert content")
content = editor.textToENML(content)
- if content is None:
- logging.error("Error while parsing text to html. Content must be an UTF-8 encode.")
- tools.exit()
result['content'] = content
@@ -565,7 +562,7 @@ def _searchNote(self, note):
logging.debug("Search notes result: %s" % str(result))
if result.totalNotes == 0:
- out.successMessage("Notes not found")
+ out.successMessage("Notes have not been found.")
return tools.exit()
elif result.totalNotes == 1 or self.selectFirstOnUpdate:
@@ -594,12 +591,13 @@ def find(self, search=None, tags=None, notebooks=None, date=None, exact_entry=No
result = self.getEvernote().findNotes(request, count, createFilter)
if result.totalNotes == 0:
- out.successMessage("Notes not found")
+ out.successMessage("Notes have not been found.")
# save search result
+ # print result
self.getStorage().setSearch(result)
- out.SearchResult(result.notes, request)
+ out.SearchResult(result.notes, request, showUrl=url_only)
def _createSearchRequest(self, search=None, tags=None, notebooks=None, date=None, exact_entry=None, content_search=None):
@@ -648,14 +646,21 @@ def _createSearchRequest(self, search=None, tags=None, notebooks=None, date=None
def modifyArgsByStdinStream():
content = sys.stdin.read()
content = tools.stdinEncode(content)
- content = editor.ENMLtoText(content)
if not content:
- out.failureMessage("Input stream is empty")
- return (None, False)
+ out.failureMessage("Input stream is empty.")
+ return tools.exit()
+
+ title = ' '.join(content.split(' ', 5)[:-1])
+ title = re.sub(r'(\r\n|\r|\n)', r' ', title)
+ if not title:
+ out.failureMessage("Error while crating title of note from stream.")
+ return tools.exit()
+ elif len(title) > 50:
+ title = title[0:50] + '...'
ARGS = {
- 'title': ' '.join(content.split(' ', 5)[:-1]),
+ 'title': title,
'content': content
}
@@ -664,7 +669,7 @@ def modifyArgsByStdinStream():
def main(args=None):
try:
# if terminal
- if sys.stdin.isatty():
+ if config.IS_IN_TERMINAL:
sys_argv = sys.argv[1:]
if isinstance(args, list):
sys_argv = args
@@ -732,6 +737,7 @@ def main(args=None):
pass
except Exception, e:
+ traceback.print_exc()
logging.error("App error: %s", str(e))
# перывание для preloader'а
View
8 oauth.py
@@ -19,7 +19,7 @@ class GeekNoteAuth(object):
consumerSecret = config.CONSUMER_SECRET
url = {
- "base" : "www.evernote.com",
+ "base" : config.USER_BASE_URL,
"oauth" : "/OAuth.action?oauth_token=%s",
"access": "/OAuth.action",
"token" : "/oauth",
@@ -50,12 +50,6 @@ class GeekNoteAuth(object):
OAuthToken = None
incorrectLogin = 0
- def __init__(self):
- if config.DEV_MODE:
- self.url['base'] = "sandbox.evernote.com"
- self.consumerKey = config.CONSUMER_KEY_SANDBOX
- self.consumerSecret = config.CONSUMER_SECRET_SANDBOX
-
def getTokenRequestData(self, **kwargs):
params = {
'oauth_consumer_key': self.consumerKey,
View
26 out.py
@@ -6,6 +6,7 @@
import thread
import tools
import editor
+import config
def preloaderPause(fn, *args, **kwargs):
def wrapped(*args, **kwargs):
@@ -36,7 +37,6 @@ def wrapped(*args, **kwargs):
class preloader(object):
- #progress = "\|/-"
progress = ("> ", ">> ", ">>>", " >>", " >", " ")
clearLine = "\r"+" "*40+"\r"
message = None
@@ -51,12 +51,16 @@ def setMessage(message, needLaunch=True):
@staticmethod
def launch():
+ if not config.IS_OUT_TERMINAL:
+ return
preloader.counter = 0
preloader.isLaunch = True
thread.start_new_thread(preloader.draw, ())
@staticmethod
def stop():
+ if not config.IS_OUT_TERMINAL:
+ return
preloader.counter = -1
preloader.draw()
preloader.isLaunch = False
@@ -91,23 +95,23 @@ def GetUserCredentials():
login = rawInput("Login: ")
if password is None:
- password = rawInput("Password: ")
+ password = rawInput("Password: ", True)
except KeyboardInterrupt:
tools.KeyboardInterruptSignalHendler(None, None)
return (login, password)
@preloaderStop
-def SearchResult(listItems, request):
+def SearchResult(listItems, request, **kwargs):
"""Печать результатов поиска"""
printLine("Search request: %s" % request)
- printList(listItems)
+ printList(listItems, **kwargs)
@preloaderStop
-def SelectSearchResult(listItems):
+def SelectSearchResult(listItems, **kwargs):
"""Выбор результата поиска"""
- return printList(listItems, showSelector=True)
+ return printList(listItems, showSelector=True, **kwargs)
@preloaderStop
@@ -171,7 +175,7 @@ def separator(symbol="", title=""):
printLine(symbol*size+"\n")
@preloaderStop
-def printList(listItems, title="", showSelector=False, showByStep=20):
+def printList(listItems, title="", showSelector=False, showByStep=20, showUrl=False):
if title:
separator("=", title)
@@ -181,10 +185,14 @@ def printList(listItems, title="", showSelector=False, showByStep=20):
for key, item in enumerate(listItems):
key += 1
- printLine("%s : %s%s" % (
+ printLine("%s : %s%s%s" % (
str(key).rjust(3, " "),
+ #print date
printDate(item.created).ljust(12, " ") if hasattr(item, 'created') else '',
- item.title if hasattr(item, 'title') else item.name))
+ #print title
+ item.title if hasattr(item, 'title') else item.name,
+ #print noteUrl
+ " "+(config.NOTE_URL % item.guid) if showUrl else '',))
if key%showByStep == 0 and key < total:
printLine("-- More --", "\r")
View
4 tools.py
@@ -62,9 +62,7 @@ def __init__(self, **entries):
self.__dict__.update(entries)
def decodeArgs(args):
- args_string = ' '.join(args)
- args_string = stdinEncode(args_string)
- return shlex.split(args_string)
+ return map(lambda val: stdinEncode(val), args)
def stdoutEncode(data):
try:

0 comments on commit 6ff24a6

Please sign in to comment.