-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnotehandler.py
357 lines (279 loc) · 10.4 KB
/
notehandler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
from __future__ import print_function
import os
import sys
import json
import time
import os.path
import hashlib
import functools
import mimetypes
import traceback
from evernote.api.client import EvernoteClient
import evernote.edam.type.ttypes as Types
import evernote.edam.notestore.ttypes as NoteTypes
import evernote.edam.error.ttypes as Errors
NOTEHANDLER_CONSUMER_KEY = ''
NOTEHANDLER_CONSUMER_SECRET = ''
NOTEHANDLER_CALLBACK_URL = ''
CONFIG_FILENAME = os.environ.get('NHRC', os.path.expanduser('~/.nhrc'))
config = None
def load_config():
global config
if config is None:
if os.path.exists(CONFIG_FILENAME):
try:
config = json.load(open(CONFIG_FILENAME,'r'))
except Exception as e:
print("Problem loading config file %s: %s" % (CONFIG_FILENAME, e))
sys.exit(1)
else:
config = {}
save_config()
def save_config():
global config
json.dump(config, open(CONFIG_FILENAME,'w')
, sort_keys=True
, indent=4
, separators=(',', ': ')
)
def debug_stderr(f):
sys.stderr.write(f())
def debug_noop(*args,**kwargs):
pass
debug = debug_noop
def memoize(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
def cmd_login(args):
"""login - Log in to Evernote; you'll be prompted for username and password"""
load_config()
if 'dev_token' in config:
access_token = config['dev_token']
elif 'access_token' in config:
access_token = config['access_token']
else:
if not ask_yn("Do you have a Dev token?"):
print("Dev token is currently required. See http://dev.evernote.com/doc/articles/authentication.php")
sys.exit(1)
access_token = raw_input("Enter it now:")
config['dev_token'] = access_token
save_config()
sandbox = config.get('sandbox', 'false').lower() != 'false'
EvernoteClient(token=access_token, sandbox=sandbox)
config['access_token'] = access_token
print("Logged in.")
def cmd_logout(args):
"""logout - Nuke your persistent Evernote credentials."""
load_config()
if 'access_token' in config:
debug(lambda: "Nuking access token %s" % config['access_token'])
del config['access_token']
save_config()
print("Logged out.")
@memoize
def get_client():
load_config()
if 'dev_token' in config:
access_token = config['dev_token']
elif 'access_token' in config:
access_token = config['access_token']
else:
print("You need to log in first.")
sys.exit(1)
sandbox = config.get('sandbox', 'false').lower() != 'false'
return EvernoteClient(token=access_token, sandbox=sandbox)
def get_note_store():
global GLOBALS
done = False
while not done:
try:
return get_client().get_note_store()
except Errors.EDAMSystemException, e:
if GLOBALS['wait'] and e.errorCode == Errors.EDAMErrorCode.RATE_LIMIT_REACHED:
towait = e.rateLimitDuration + 1
print("Rate limit reached; waiting the suggested %d seconds..." % towait)
time.sleep(towait)
else:
raise e
def get_notebooks():
return get_note_store().listNotebooks()
def get_current_notebook_name():
load_config()
if 'cur_notebook' in config:
if not config['cur_notebook'] in [ n.name for n in get_notebooks() ]:
del config['cur_notebook']
if 'cur_notebook' not in config:
cur = [ n.name for n in get_notebooks() if n.defaultNotebook ]
if len(cur) < 1:
cur = get_notebooks()[0].name
config['cur_notebook'] = cur[0]
save_config()
return config['cur_notebook']
def get_current_notebook():
return [n for n in get_notebooks() if n.name == get_current_notebook_name()][0]
def ask_yn(prompt):
result = raw_input(prompt)
return result.lower() in [ 'y', 'yes' ]
def set_current_notebook_name(name):
load_config()
if name not in [ n.name for n in get_notebooks() ]:
if not ask_yn("Notebook '%s' doesn't exist. Create it?" % name):
print("Aborted.")
sys.exit(1)
notebook = Types.Notebook()
notebook.name = name
notebook = get_note_store().createNotebook(notebook)
config['cur_notebook'] = name
save_config()
def cmd_notebooks(args):
"""notebooks - List existing notebooks.
The (evernote) default notebook is marked with a 'D'.
The (local-only) current notebook is marked with a '+'
"""
get_client()
print("Notebooks:")
for n in get_notebooks():
print(" %s%s%s" % ( 'D' if n.defaultNotebook else ' '
, '+' if n.name == get_current_notebook_name() else ' '
, n.name))
def cmd_notebook(args):
"""notebook [+<notebook>] - if notebook is specified, set the current notebook,
creating it if necessary. Otherwise, just show the current notebook.
"""
if len(args) > 0:
name = args[0]
if name.startswith('+'): name = name[1:]
set_current_notebook_name(name)
print("Current notebook set to '%s'." % get_current_notebook_name())
def cmd_notes(args, offset=0, count=10):
"""notes [+notebook] [[:tag1 [:tag2] ...] [--offset=X] [--count=Y] -
list notes in the specified notebook, or the current one if not specified.
"""
tags = []
for arg in args:
if arg.startswith('+'):
set_current_notebook_name(arg[1:])
if arg.startswith(':'):
tags.append(arg[1:])
nb_guid = get_current_notebook().guid
nf = NoteTypes.NoteFilter( notebookGuid=nb_guid )
nb_tags = get_note_store().listTagsByNotebook( nb_guid ) or []
if tags:
nf.tagGuids = [ t.guid for t in nb_tags if t.name in tags ]
resultspec = NoteTypes.NotesMetadataResultSpec()
for field in ['includeTitle', 'includeUpdated', 'includeTagGuids']:
setattr(resultspec, field, True)
notesml = get_note_store().findNotesMetadata(nf, int(offset), int(count), resultspec)
debug(lambda: "Notes in notebook '%s': " % get_current_notebook_name())
for note in notesml.notes:
notetags = note.tagGuids or []
tagdisplay = [ "[%s]" % t.name for t in nb_tags if t.guid in notetags ]
updatedisplay = time.strftime("%m/%d", time.localtime(note.updated / 1000))
print(" %s %s %s %s" % (note.guid, updatedisplay, tagdisplay, note.title))
remaining = notesml.totalNotes - notesml.startIndex - len(notesml.notes)
if remaining > 0:
print("...and %d more." % remaining)
def cmd_show(args):
"""show <guid> [[guid1] [guid2] ...] - show the specified note(s) (in ENML)
"""
if not len(args) > 0:
raise SyntaxError
ns = get_note_store()
withContent=True
withResourcesData=False
withResourcesRecognition=False
withResourcesAlternateData=False
for guid in args:
note = ns.getNote(guid, withContent, withResourcesData, withResourcesRecognition, withResourcesAlternateData)
print("Title: %s\n\n%s\n" % (note.title, note.content))
def cmd_add(args):
"""add [[:tag1] [:tag2] ...]
[+<notebook>]
<title>
[resource1] [resource2] ..
< <content>
add a new note
with the specified tags (or none if unspecified)
in the specified notebook (or your current notebook if unspecified)
with the specified title (required)
adding the specified files as resources to that note (or none if unspecified)
and content from stdin
"""
# Parse args
tags = []
title = None
resource_names = []
for arg in args:
if arg.startswith('+'):
set_current_notebook_name(arg[1:])
elif arg.startswith(':'):
tags.append(arg[1:])
elif title is None:
title = arg
else:
resource_names.append(arg)
if title is None:
print("A title must be specified.")
raise SyntaxError
print("making note titled '%s' with tags'%s' and resources named '%s'" % (title, repr(tags), repr(resource_names)))
nb_guid = get_current_notebook().guid
resources = []
attachments = ""
for filename in resource_names:
resource = Types.Resource()
resource.data = Types.Data()
resource.data.body = open(filename,'r').read()
resource.attributes = Types.ResourceAttributes(fileName=filename,attachment=False)
mime = mimetypes.guess_type(filename)[0]
resource.mime = mime or ''
hash = hashlib.md5()
hash.update(resource.data.body)
attachments += '<en-media type="%s" hash="%s" />\n' % (resource.mime, hash.hexdigest())
resources.append(resource)
content = wrap_content(sys.stdin.read() + attachments)
note = Types.Note(title=title, content=content, tagNames=tags, resources=resources, notebookGuid=nb_guid)
note = _retry(lambda: get_note_store().createNote(note))
print("Note created!")
def _retry(f,n=3):
for tries in range(n):
try:
return f()
except:
print("Problem: %s \n Retrying..." % traceback.format_exc())
pass
print("Failed! Exiting!")
sys.exit(1)
def wrap_content(content):
return """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
<en-note>""" + content + "</en-note>"
def cmd_userinfo(args):
"""userinfo - Show your settings and information."""
client = get_client()
userStore = client.get_user_store()
user = userStore.getUser()
for field in [ 'name', 'username', 'email', 'timezone', 'privilege', 'active', 'created', 'updated', 'deleted', 'attributes' ]:
value = str(getattr(user, field, ''))
print("%s: %s" % (field.capitalize(), value))
GLOBALS = { 'wait': True }
def _handle_globals(args):
global GLOBALS
newargs = []
for arg in args:
if arg.lower() == '--wait':
GLOBALS['wait'] = True
elif arg.lower() == '--no-wait':
GLOBALS['wait'] = False
else:
newargs.append(arg)
return newargs
def main():
from cmdpy import CmdfileClient
args = _handle_globals(sys.argv[1:])
CmdfileClient(cmdmodule='notehandler').execute(args)