def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception, e: logging.error("Error: %s : %s", func.__name__, str(e)) if not hasattr(e, 'errorCode'): out.failureMessage("Sorry, operation has failed!!!.") tools.exitErr() errorCode = int(e.errorCode) # auth-token error, re-auth if errorCode == 9: storage = Storage() storage.removeUser() GeekNote() return func(*args, **kwargs) elif errorCode == 3: out.failureMessage("Sorry, you do not have permissions " "to do this operation.") else: return False tools.exitErr()
def createNote(self, title, content, tags=None, created=None, notebook=None, resources=None, reminder=None): note = Types.Note() note.title = title try: note.content = content.encode('utf-8') except UnicodeDecodeError: note.content = content if tags: note.tagNames = tags note.created = created if notebook: note.notebookGuid = notebook if resources: """ make EverNote API resources """ note.resources = map(make_resource, resources) """ add to content """ resource_nodes = "" for resource in note.resources: resource_nodes += '<en-media type="%s" hash="%s" />' % ( resource.mime, resource.data.bodyHash) note.content = note.content.replace("</en-note>", resource_nodes + "</en-note>") # Allow creating a completed reminder (for task tracking purposes), # skip reminder creation steps if we have a DELETE if reminder and reminder != config.REMINDER_DELETE: now = int(round(time.time() * 1000)) note.attributes = Types.NoteAttributes() if reminder == config.REMINDER_NONE: note.attributes.reminderOrder = now elif reminder == config.REMINDER_DONE: note.attributes.reminderOrder = now note.attributes.reminderDoneTime = now else: # we have an actual reminder time stamp if reminder > now: # future reminder only note.attributes.reminderOrder = now note.attributes.reminderTime = reminder else: out.failureMessage( "Error: reminder must be in the future.") tools.exitErr() logging.debug("New note : %s", note) return self.getNoteStore().createNote(self.authToken, note)
def createNote( self, title, content, tags=None, created=None, notebook=None, resources=None, reminder=None, url=None ): note = Types.Note() note.title = title try: note.content = content.encode("utf-8") except UnicodeDecodeError: note.content = content if tags: note.tagNames = tags note.created = created if notebook: note.notebookGuid = notebook if resources: """ make EverNote API resources """ note.resources = map(make_resource, resources) """ add to content """ resource_nodes = "" for resource in note.resources: resource_nodes += '<en-media type="%s" hash="%s" />' % (resource.mime, resource.data.bodyHash) note.content = note.content.replace("</en-note>", resource_nodes + "</en-note>") # Allow creating a completed reminder (for task tracking purposes), # skip reminder creation steps if we have a DELETE if reminder and reminder != config.REMINDER_DELETE: if not note.attributes: # in case no attributes available note.attributes = Types.NoteAttributes() now = int(round(time.time() * 1000)) if reminder == config.REMINDER_NONE: note.attributes.reminderOrder = now elif reminder == config.REMINDER_DONE: note.attributes.reminderOrder = now note.attributes.reminderDoneTime = now else: # we have an actual reminder time stamp if reminder > now: # future reminder only note.attributes.reminderOrder = now note.attributes.reminderTime = reminder else: out.failureMessage("Error: reminder must be in the future.") tools.exitErr() if url: if note.attributes is None: note.attributes = Types.NoteAttributes() note.attributes.sourceURL = url logging.debug("New note : %s", note) return self.getNoteStore().createNote(self.authToken, note)
def loadPage(self, url, uri=None, method="GET", params="", additionalParams=""): if not url: logging.error("Request URL undefined") tools.exitErr() if not uri: urlData = urlparse(url) url = urlData.netloc uri = urlData.path + '?' + urlData.query # prepare params, append to uri if params: params = urlencode(params) + additionalParams if method == "GET": uri += ('?' if uri.find('?') == -1 else '&') + params params = "" # insert local cookies in request headers = { "Cookie": '; '.join( [key + '=' + self.cookies[key] for key in self.cookies.keys()]) } if method == "POST": headers["Content-type"] = "application/x-www-form-urlencoded" logging.debug("Request URL: %s:/%s > %s # %s", url, uri, unquote(params), headers["Cookie"]) conn = httplib.HTTPSConnection(url) conn.request(method, uri, params, headers) response = conn.getresponse() data = response.read() conn.close() logging.debug("Response : %s > %s", response.status, response.getheaders()) result = tools.Struct(status=response.status, location=response.getheader('location', None), data=data) # update local cookies sk = Cookie.SimpleCookie(response.getheader("Set-Cookie", "")) for key in sk: self.cookies[key] = sk[key].value # delete cookies whose content is "deleteme" for key in self.cookies.keys(): if self.cookies[key] == "deleteme": del self.cookies[key] return result
def login(self): if self.getEvernote().checkAuth(): out.failureMessage("You have already logged in.") return tools.exitErr() if self.getEvernote().auth(): out.successMessage("You have successfully logged in.") else: out.failureMessage("Login error.") return tools.exitErr()
def loadPage(self, url, uri=None, method="GET", params=""): if not url: logging.error("Request URL undefined") tools.exitErr() if not uri: urlData = urlparse(url) url = urlData.netloc uri = urlData.path + '?' + urlData.query # prepare params, append to uri if params: params = urlencode(params) if method == "GET": uri += ('?' if uri.find('?') == -1 else '&') + params params = "" # insert local cookies in request headers = { "Cookie": '; '.join([key + '=' + self.cookies[key] for key in self.cookies.keys()]) } if method == "POST": headers["Content-type"] = "application/x-www-form-urlencoded" logging.debug("Request URL: %s:/%s > %s # %s", url, uri, unquote(params), headers["Cookie"]) conn = httplib.HTTPSConnection(url) conn.request(method, uri, params, headers) response = conn.getresponse() data = response.read() conn.close() logging.debug("Response : %s > %s", response.status, response.getheaders()) result = tools.Struct(status=response.status, location=response.getheader('location', None), data=data) # update local cookies sk = Cookie.SimpleCookie(response.getheader("Set-Cookie", "")) for key in sk: self.cookies[key] = sk[key].value # delete cookies whose content is "deleteme" for key in self.cookies.keys(): if self.cookies[key] == "deleteme": del self.cookies[key] return result
def logout(self, force=None): if not self.getEvernote().checkAuth(): out.failureMessage("You have already logged out.") return tools.exitErr() 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("You have successfully logged out.") else: out.failureMessage("Logout error.") return tools.exitErr()
def allowAccess(self): response = self.loadPage(self.url['base'], self.url['access'], "GET", {'oauth_token': self.tmpOAuthToken}) logging.debug(response.data) tree = html.fromstring(response.data) token = "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[0] }) + "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[1] }) sourcePage = tree.xpath("//input[@name='_sourcePage']/@value")[0] fp = tree.xpath("//input[@name='__fp']/@value")[0] targetUrl = tree.xpath("//input[@name='targetUrl']/@value")[0] logging.debug(token) if response.status != 200: logging.error("Unexpected response status " "on login 200 != %s", response.status) tools.exitErr() if 'JSESSIONID' not in self.cookies: logging.error("Not found value JSESSIONID in the response cookies") tools.exitErr() access = self.postData['access'] access['oauth_token'] = self.tmpOAuthToken access['oauth_callback'] = "" access['embed'] = 'false' access['suggestedNotebookName'] = 'Geeknote' access['supportLinkedSandbox'] = '' access['analyticsLoginOrigin'] = 'Other' access['clipperFlow'] = 'false' access['showSwitchService'] = 'true' access['_sourcePage'] = sourcePage access['__fp'] = fp access['targetUrl'] = targetUrl response = self.loadPage(self.url['base'], self.url['access'], "POST", access, token) if response.status != 302: logging.error( "Unexpected response status on allowing " "access 302 != %s", response.status) logging.error(response.data) tools.exitErr() responseData = self.parseResponse(response.location) if 'oauth_verifier' not in responseData: logging.error("OAuth verifier not found") tools.exitErr() self.verifierToken = responseData['oauth_verifier'] logging.debug("OAuth verifier token take")
def edit(self, note, title=None, content=None, tag=None, created=None, notebook=None, resource=None, reminder=None, url=None, raw=None): self.connectToEvernote() note = self._searchNote(note) inputData = self._parseInput(title, content, tag, created, notebook, resource, note, reminder, url) if inputData['content'] == config.EDITOR_OPEN: result = self._editWithEditorInThread(inputData, note, raw=raw) else: out.preloader.setMessage("Saving note...") result = bool(self.getEvernote().updateNote(guid=note.guid, **inputData)) if result: out.successMessage("Note successfully saved.") else: out.failureMessage("Error: could not save note.") return tools.exitErr()
def checkVersion(self): versionOK = self.getUserStore().checkVersion("Python EDAMTest", UserStoreConstants.EDAM_VERSION_MAJOR, UserStoreConstants.EDAM_VERSION_MINOR) if not versionOK: logging.error("Old EDAM version") return tools.exitErr()
def find( self, search=None, tags=None, notebooks=None, date=None, exact_entry=None, content_search=None, with_url=None, count=None, ): request = self._createSearchRequest(search, tags, notebooks, date, exact_entry, content_search) if not count: count = 20 else: count = int(count) logging.debug("Search count: %s", count) createFilter = True if search == "*" else False result = self.getEvernote().findNotes(request, count, createFilter) if result.totalNotes == 0: out.failureMessage("Notes have not been found.") return tools.exitErr() # save search result # print result self.getStorage().setSearch(result) out.SearchResult(result.notes, request, showUrl=with_url)
def edit( self, note, title=None, content=None, tag=None, created=None, notebook=None, resource=None, reminder=None, url=None, raw=None, ): self.connectToEvernote() note = self._searchNote(note) inputData = self._parseInput(title, content, tag, created, notebook, resource, note, reminder, url) if inputData["content"] == config.EDITOR_OPEN: result = self._editWithEditorInThread(inputData, note, raw=raw) else: out.preloader.setMessage("Saving note...") result = bool(self.getEvernote().updateNote(guid=note.guid, **inputData)) if result: out.successMessage("Note successfully saved.") else: out.failureMessage("Error: could not save note.") return tools.exitErr()
def create( self, title, content=None, tag=None, created=None, notebook=None, resource=None, reminder=None, url=None, raw=None, ): self.connectToEvernote() # Optional Content. content = content or " " inputData = self._parseInput(title, content, tag, created, notebook, resource, None, reminder, url) if inputData["content"] == config.EDITOR_OPEN: result = self._editWithEditorInThread(inputData, raw=raw) else: out.preloader.setMessage("Creating note...") result = bool(self.getEvernote().createNote(**inputData)) if result: out.successMessage("Note successfully created.") else: out.failureMessage("Error: could not create note.") return tools.exitErr()
def _searchNote(self, note): note = tools.strip(note) # load search result result = self.getStorage().getSearch() if result and tools.checkIsInt(note) and 1 <= int(note) <= len(result.notes): note = result.notes[int(note) - 1] else: request = self._createSearchRequest(search=note) logging.debug("Search notes: %s" % request) result = self.getEvernote().findNotes(request, 20) logging.debug("Search notes result: %s" % str(result)) if result.totalNotes == 0: out.failureMessage("Notes have not been found.") return tools.exitErr() elif result.totalNotes == 1 or self.selectFirstOnUpdate: note = result.notes[0] else: logging.debug("Choose notes: %s" % str(result.notes)) note = out.SelectSearchResult(result.notes) logging.debug("Selected note: %s" % str(note)) return note
def textToENML(content, raise_ex=False, format='markdown'): """ Create an ENML format of note. """ if not isinstance(content, str): content = "" try: content = unicode(content, "utf-8") # add 2 space before new line in paragraph for creating br tags content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1 \n\3', content) if format=='markdown': contentHTML = markdown.markdown(content).encode("utf-8") # Non-Pretty HTML output contentHTML = str(BeautifulSoup(contentHTML, 'html.parser')) else: contentHTML = Editor.HTMLEscape(content) return Editor.wrapENML(contentHTML) except: if raise_ex: raise Exception("Error while parsing text to html." " Content must be an UTF-8 encode.") 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.exitErr()
def _createSearchRequest(self, search=None, tags=None, notebooks=None, date=None, exact_entry=None, content_search=None): request = "" if notebooks: for notebook in tools.strip(notebooks.split(',')): if notebook.startswith('-'): request += '-notebook:"%s" ' % tools.strip(notebook[1:]) else: request += 'notebook:"%s" ' % tools.strip(notebook) if tags: for tag in tools.strip(tags.split(',')): if tag.startswith('-'): request += '-tag:"%s" ' % tag[1:] else: request += 'tag:"%s" ' % tag if date: date = tools.strip(date.split('-')) try: dateStruct = time.strptime(date[0] + " 00:00:00", "%d.%m.%Y %H:%M:%S") request += 'created:%s ' % time.strftime("%Y%m%d", time.localtime(time.mktime(dateStruct))) if len(date) == 2: dateStruct = time.strptime(date[1] + " 00:00:00", "%d.%m.%Y %H:%M:%S") request += '-created:%s ' % time.strftime("%Y%m%d", time.localtime(time.mktime(dateStruct) + 60 * 60 * 24)) except ValueError, e: out.failureMessage('Incorrect date format in --date attribute. ' 'Format: %s' % time.strftime("%d.%m.%Y", time.strptime('19991231', "%Y%m%d"))) return tools.exitErr()
def find(self, search=None, tag=None, notebooks=None, date=None, exact_entry=None, content_search=None, with_url=None, with_tags=None, with_notebook=None, count=None, ignore_completed=None, reminders_only=None, guid=None): request = self._createSearchRequest(search, tag, notebooks, date, exact_entry, content_search, ignore_completed, reminders_only) if not count: count = 20 else: count = int(count) logging.debug("Search count: %s", count) createFilter = True if search == "*" else False result = self.getEvernote().findNotes(request, count, createFilter) if result.totalNotes == 0: out.failureMessage("Notes have not been found.") return tools.exitErr() # save search result # print result self.getStorage().setSearch(result) for note in result.notes: self.getStorage().setNote(note) out.SearchResult(result.notes, request, showUrl=with_url, showTags=with_tags, showNotebook=with_notebook, showGUID=guid)
def find(self, search=None, tags=None, notebooks=None, date=None, exact_entry=None, content_search=None, with_url=None, count=None, ignore_completed=None, reminders_only=None,): request = self._createSearchRequest(search, tags, notebooks, date, exact_entry, content_search, ignore_completed, reminders_only) if not count: count = 20 else: count = int(count) logging.debug("Search count: %s", count) createFilter = True if search == "*" else False result = self.getEvernote().findNotes(request, count, createFilter) if result.totalNotes == 0: out.failureMessage("Notes have not been found.") return tools.exitErr() # save search result # print result self.getStorage().setSearch(result) out.SearchResult(result.notes, request, showUrl=with_url)
def create(self, title, content=None, tag=None, created=None, notebook=None, resource=None, reminder=None, url=None, raw=None): self.connectToEvernote() # Optional Content. content = content or " " inputData = self._parseInput(title, content, tag, created, notebook, resource, None, reminder, url) if inputData['content'] == config.EDITOR_OPEN: result = self._editWithEditorInThread(inputData, raw=raw) else: out.preloader.setMessage("Creating note...") result = bool(self.getEvernote().createNote(**inputData)) if result: out.successMessage("Note successfully created.") else: out.failureMessage("Error: could not create note.") return tools.exitErr()
def handleTwoFactor(self): self.code = out.GetUserAuthCode() self.postData['tfa']['code'] = self.code response = self.loadPage(self.url['base'], self.url['tfa'] + ";jsessionid=" + self.cookies['JSESSIONID'], "POST", self.postData['tfa']) if not response.location and response.status == 200: if self.incorrectCode < 3: out.preloader.stop() out.printLine('Sorry, incorrect two factor code') out.preloader.setMessage('Authorize...') self.incorrectCode += 1 return self.handleTwoFactor() else: logging.error("Incorrect two factor code") if not response.location: logging.error("Target URL was not found in the response on login") tools.exitErr()
def _parseInput(self, title=None, content=None, tags=None, notebook=None, resources=[], note=None, reminder=None): result = { "title": title, "content": content, "tags": tags, "notebook": notebook, "resources": resources, "reminder": reminder, } result = tools.strip(result) # if get note without params if note and title is None and content is None and tags is None and notebook is None: content = config.EDITOR_OPEN if title is None and note: result['title'] = note.title if content: if content != config.EDITOR_OPEN: if isinstance(content, str) and os.path.isfile(content): logging.debug("Load content from the file") content = open(content, "r").read() logging.debug("Convert content") content = Editor.textToENML(content) result['content'] = content if tags: result['tags'] = tools.strip(tags.split(',')) if notebook: notepadGuid = Notebooks().getNoteGUID(notebook) if notepadGuid is None: newNotepad = Notebooks().create(notebook) notepadGuid = newNotepad.guid result['notebook'] = notepadGuid logging.debug("Search notebook") if reminder: then = config.REMINDER_SHORTCUTS.get(reminder) if then: now = int(round(time.time() * 1000)) result['reminder'] = now + then elif reminder not in [config.REMINDER_NONE, config.REMINDER_DONE, config.REMINDER_DELETE]: reminder = tools.strip(reminder.split('-')) try: dateStruct = time.strptime(reminder[0] + " " + reminder[1] + ":00", config.DEF_DATE_AND_TIME_FORMAT) reminderTime = int(round(time.mktime(dateStruct) * 1000)) result['reminder'] = reminderTime except (ValueError, IndexError): out.failureMessage('Incorrect date format in --reminder attribute. ' 'Format: %s' % time.strftime(config.DEF_DATE_FORMAT, time.strptime('199912311422', "%Y%m%d%H%M"))) return tools.exitErr() return result
def allowAccess(self): response = self.loadPage(self.url['base'], self.url['access'], "GET", {'oauth_token': self.tmpOAuthToken}) logging.debug(response.data) tree = html.fromstring(response.data); token = "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[0]}) + "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[1]}) sourcePage = tree.xpath("//input[@name='_sourcePage']/@value")[0] fp = tree.xpath("//input[@name='__fp']/@value")[0] targetUrl = tree.xpath("//input[@name='targetUrl']/@value")[0] logging.debug(token); if response.status != 200: logging.error("Unexpected response status " "on login 200 != %s", response.status) tools.exitErr() if 'JSESSIONID' not in self.cookies: logging.error("Not found value JSESSIONID in the response cookies") tools.exitErr() access = self.postData['access'] access['oauth_token'] = self.tmpOAuthToken access['oauth_callback'] = "" access['embed'] = 'false' access['suggestedNotebookName'] = 'Geeknote' access['supportLinkedSandbox'] = '' access['analyticsLoginOrigin'] = 'Other' access['clipperFlow'] = 'false' access['showSwitchService'] = 'true' access['_sourcePage'] = sourcePage access['__fp'] = fp access['targetUrl'] = targetUrl response = self.loadPage(self.url['base'], self.url['access'], "POST", access, token) if response.status != 302: logging.error("Unexpected response status on allowing " "access 302 != %s", response.status) logging.error(response.data) tools.exitErr() responseData = self.parseResponse(response.location) if 'oauth_verifier' not in responseData: logging.error("OAuth verifier not found") tools.exitErr() self.verifierToken = responseData['oauth_verifier'] logging.debug("OAuth verifier token take")
def user(self, full=None): if not self.getEvernote().checkAuth(): out.failureMessage("You are not logged in.") return tools.exitErr() if full: info = self.getEvernote().getUserInfo() else: info = self.getStorage().getUserInfo() out.showUser(info, full)
def getOAuthToken(self): response = self.loadPage( self.url['base'], self.url['token'], "GET", self.getTokenRequestData(oauth_token=self.tmpOAuthToken, oauth_verifier=self.verifierToken)) if response.status != 200: logging.error( "Unexpected response status on " "getting oauth token 200 != %s", response.status) tools.exitErr() responseData = self.parseResponse(response.data) if 'oauth_token' not in responseData: logging.error("OAuth token not found") tools.exitErr() logging.debug("OAuth token take : %s", responseData['oauth_token']) self.OAuthToken = responseData['oauth_token']
def modifyArgsByStdinStream(): """Parse the stdin stream for arguments""" content = sys.stdin.read() content = tools.stdinEncode(content) if not content: out.failureMessage("Input stream is empty.") return tools.exitErr() title = ' '.join(content.split(' ', 5)[:-1]) title = re.sub(r'(\r\n|\r|\n)', r' ', title) if not title: out.failureMessage("Error while creating title of note from stream.") return tools.exitErr() elif len(title) > 50: title = title[0:50] + '...' ARGS = {'title': title, 'content': content} return ('create', ARGS)
def getTmpOAuthToken(self): response = self.loadPage( self.url['base'], self.url['token'], "GET", self.getTokenRequestData(oauth_callback="https://" + self.url['base'])) if response.status != 200: logging.error( "Unexpected response status on get " "temporary oauth_token 200 != %s", response.status) tools.exitErr() responseData = self.parseResponse(response.data) if 'oauth_token' not in responseData: logging.error("OAuth temporary not found") tools.exitErr() self.tmpOAuthToken = responseData['oauth_token'] logging.debug("Temporary OAuth token : %s", self.tmpOAuthToken)
def getTmpOAuthToken(self): response = self.loadPage(self.url['base'], self.url['token'], "GET", self.getTokenRequestData( oauth_callback="https://" + self.url['base'])) if response.status != 200: logging.error("Unexpected response status on get " "temporary oauth_token 200 != %s", response.status) tools.exitErr() responseData = self.parseResponse(response.data) if 'oauth_token' not in responseData: logging.error("OAuth temporary not found") tools.exitErr() self.tmpOAuthToken = responseData['oauth_token'] logging.debug("Temporary OAuth token : %s", self.tmpOAuthToken)
def getOAuthToken(self): response = self.loadPage(self.url['base'], self.url['token'], "GET", self.getTokenRequestData( oauth_token=self.tmpOAuthToken, oauth_verifier=self.verifierToken)) if response.status != 200: logging.error("Unexpected response status on " "getting oauth token 200 != %s", response.status) tools.exitErr() responseData = self.parseResponse(response.data) if 'oauth_token' not in responseData: logging.error("OAuth token not found") tools.exitErr() logging.debug("OAuth token take : %s", responseData['oauth_token']) self.OAuthToken = responseData['oauth_token']
def edit(self, notebook, title): notebook = self._searchNotebook(notebook) out.preloader.setMessage("Updating notebook...") result = self.getEvernote().updateNotebook(guid=notebook.guid, name=title) if result: out.successMessage("Notebook has been successfully updated.") else: out.failureMessage("Error while the updating the notebook.") return tools.exitErr()
def edit(self, tagname, title): tag = self._searchTag(tagname) out.preloader.setMessage("Updating tag...") result = self.getEvernote().updateTag(guid=tag.guid, name=title) if result: out.successMessage("Tag has been successfully updated.") else: out.failureMessage("Error while the updating the tag.") return tools.exitErr()
def find( self, search=None, tag=None, notebook=None, date=None, exact_entry=None, content_search=None, with_url=None, with_tags=None, with_notebook=None, count=None, ignore_completed=None, reminders_only=None, guid=None, ): request = self._createSearchRequest( search, tag, notebook, date, exact_entry, content_search, ignore_completed, reminders_only ) if not count: count = 20 else: count = int(count) logging.debug("Search count: %s", count) createFilter = True if search == "*" else False result = self.getEvernote().findNotes(request, count, createFilter) if result.totalNotes == 0: out.failureMessage("Notes have not been found.") return tools.exitErr() # save search result # print result self.getStorage().setSearch(result) for note in result.notes: self.getStorage().setNote(note) if with_notebook: noteStore = self.getEvernote().getNoteStore() notebookNameFromGuid = dict() for note in result.notes: if note.notebookGuid not in notebookNameFromGuid: notebookNameFromGuid[note.notebookGuid] = noteStore.getNotebook( self.getEvernote().authToken, note.notebookGuid ).name note.notebookName = notebookNameFromGuid[note.notebookGuid] out.SearchResult( result.notes, request, showUrl=with_url, showTags=with_tags, showNotebook=with_notebook, showGUID=guid )
def create(self, title, stack=None): self.connectToEvernote() out.preloader.setMessage("Creating notebook...") result = self.getEvernote().createNotebook(name=title, stack=stack) if result: out.successMessage("Notebook successfully created.") else: out.failureMessage("Error: could not create notebook.") return tools.exitErr() return result
def create(self, title): self.connectToEvernote() out.preloader.setMessage("Creating tag...") result = self.getEvernote().createTag(name=title) if result: out.successMessage("Tag successfully created.") else: out.failureMessage("Error: tag could not be created.") return tools.exitErr() return result
def allowAccess(self): access = self.postData['access'] access['oauth_token'] = self.tmpOAuthToken access['oauth_callback'] = "https://" + self.url['base'] response = self.loadPage(self.url['base'], self.url['access'], "POST", access) if response.status != 302: logging.error("Unexpected response status on allowing " "access 302 != %s", response.status) tools.exitErr() responseData = self.parseResponse(response.location) if 'oauth_verifier' not in responseData: logging.error("OAuth verifier not found") tools.exitErr() self.verifierToken = responseData['oauth_verifier'] logging.debug("OAuth verifier token take")
def allowAccess(self): access = self.postData['access'] access['oauth_token'] = self.tmpOAuthToken access['oauth_callback'] = "https://" + self.url['base'] response = self.loadPage(self.url['base'], self.url['access'], "POST", access) if response.status != 302: logging.error( "Unexpected response status on allowing " "access 302 != %s", response.status) tools.exitErr() responseData = self.parseResponse(response.location) if 'oauth_verifier' not in responseData: logging.error("OAuth verifier not found") tools.exitErr() self.verifierToken = responseData['oauth_verifier'] logging.debug("OAuth verifier token take")
def create(self, title): self.connectToEvertone() out.preloader.setMessage("Creating tag...") result = self.getEvernote().createTag(name=title) if result: out.successMessage("Tag has been successfully created.") else: out.failureMessage("Error while the process of creating the tag.") return tools.exitErr() return result
def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception, e: logging.error("Error: %s : %s", func.__name__, str(e)) if not hasattr(e, 'errorCode'): out.failureMessage("Sorry, operation has failed!!!.") tools.exitErr() errorCode = int(e.errorCode) # auth-token error, re-auth if errorCode == 9: storage = Storage() storage.removeUser() GeekNote() return func(*args, **kwargs) elif errorCode == 3: out.failureMessage("Sorry, you do not have permissions " "to do this operation.") # Rate limited # Patched because otherwise if you get rate limited you still keep # hammering the server on scripts elif errorCode == 19: print("\nRate Limit Hit: Please wait %s seconds before continuing" % str(e.rateLimitDuration)) tools.exitErr() else: return False tools.exitErr()
def remove(self, notebook, force=None): notebook = self._searchNotebook(notebook) if not force and not out.confirm("Are you sure you want to delete" ' this notebook: "%s"?' % notebook.name): return tools.exit() out.preloader.setMessage("Deleting notebook...") result = self.getEvernote().removeNotebook(guid=notebook.guid) if result: out.successMessage("Notebook successfully removed.") else: out.failureMessage("Error: could not remove notebook.") return tools.exitErr()
def modifyArgsByStdinStream(): """Parse the stdin stream for arguments""" content = sys.stdin.read() content = tools.stdinEncode(content) if not content: out.failureMessage("Input stream is empty.") return tools.exitErr() title = ' '.join(content.split(' ', 5)[:-1]) title = re.sub(r'(\r\n|\r|\n)', r' ', title) if not title: out.failureMessage("Error while creating title of note from stream.") return tools.exitErr() elif len(title) > 50: title = title[0:50] + '...' ARGS = { 'title': title, 'content': content } return ('create', ARGS)
def remove(self, tagname, force=None): tag = self._searchTag(tagname) if not force and not out.confirm("Are you sure you want to " 'delete the tag "%s"?' % tag.name): return tools.exit() out.preloader.setMessage("Deleting tag...") result = self.getEvernote().removeTag(guid=tag.guid) if result: out.successMessage("Tag successfully removed.") else: out.failureMessage("Error: tag could not be removed.") return tools.exitErr()
def textToENML(content, raise_ex=False, format='markdown'): """ Create an ENML format of note. """ if not isinstance(content, str): content = "" try: content = unicode(content, "utf-8") # add 2 space before new line in paragraph for creating br tags content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1 \n\3', content) if format == 'markdown': storage = Storage() extras = storage.getUserprop('markdown2_extras') #contentHTML = markdown.markdown(content).encode("utf-8") contentHTML = markdown.markdown(content, extras=extras).encode("utf-8") soup = BeautifulSoup(contentHTML, 'html.parser') Editor.checklistInSoupToENML(soup) # Non-Pretty HTML output contentHTML = str(soup) # # For the 'pre' format, simply wrap the content with a 'pre' tag. Do # perform any parsing/mutation. # elif format == 'pre': contentHTML = u''.join( ('<pre>', content, '</pre>')).encode("utf-8") else: contentHTML = Editor.HTMLEscape(content) contentHTML = contentHTML.replace( '[x]', '<en-todo checked="true"></en-todo>') contentHTML = contentHTML.replace('[ ]', '<en-todo></en-todo>') return Editor.wrapENML(contentHTML) except: import traceback traceback.print_exc() if raise_ex: raise Exception("Error while parsing text to html." " Content must be an UTF-8 encode.") 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.exitErr()
def remove(self, tagname, force=None): tag = self._searchTag(tagname) if not force and not out.confirm('Are you sure you want to ' 'delete the tag "%s"?' % tag.name): return tools.exit() out.preloader.setMessage("Deleting tag...") result = self.getEvernote().removeTag(guid=tag.guid) if result: out.successMessage("Tag successfully removed.") else: out.failureMessage("Error: tag could not be removed.") return tools.exitErr()
def login(self): response = self.loadPage( self.url["base"], self.url["login"], "GET", {"oauth_token": self.tmpOAuthToken}, ) # parse hpts and hptsh from page content hpts = re.search('.*\("hpts"\)\.value.*?"(.*?)"', response.data) hptsh = re.search('.*\("hptsh"\)\.value.*?"(.*?)"', response.data) if response.status != 200: logging.error( "Unexpected response status " "on login 200 != %s", response.status ) tools.exitErr() if "JSESSIONID" not in self.cookies: logging.error("Not found value JSESSIONID in the response cookies") tools.exitErr() # get login/password self.username, self.password = out.GetUserCredentials() self.postData["login"]["username"] = self.username self.postData["login"]["password"] = self.password self.postData["login"]["targetUrl"] = self.url["oauth"] % self.tmpOAuthToken self.postData["login"]["hpts"] = hpts and hpts.group(1) or "" self.postData["login"]["hptsh"] = hptsh and hptsh.group(1) or "" response = self.loadPage( self.url["base"], self.url["login"] + ";jsessionid=" + self.cookies["JSESSIONID"], "POST", self.postData["login"], ) if not response.location and response.status == 200: if self.incorrectLogin < 3: out.preloader.stop() out.printLine("Sorry, incorrect login or password") out.preloader.setMessage("Authorize...") self.incorrectLogin += 1 return self.login() else: logging.error("Incorrect login or password") if not response.location: logging.error("Target URL was not found in the response on login") tools.exitErr() if response.status == 302: # the user has enabled two factor auth return self.handleTwoFactor() logging.debug("Success authorize, redirect to access page")
def _getTimeFromDate(self, date): dateStruct = None for fmt in config.DEF_DATE_FORMAT, config.DEF_DATE_AND_TIME_FORMAT: try: dateStruct = time.strptime(date, fmt) except ValueError: pass if not dateStruct: out.failureMessage( 'Error while parsing date: "%s" is in an ' "incorrect format. Dates should\nbe specified as " '"yyyy-mm-dd" or "yyyy-mm-dd HH:MM" strings.' % date ) return tools.exitErr() return int(round(time.mktime(dateStruct) * 1000))
def remove(self, notebook, force=None): notebook = self._searchNotebook(notebook) if not force and not out.confirm('Are you sure you want to delete' ' this notebook: "%s"?' % notebook.name): return tools.exit() out.preloader.setMessage("Deleting notebook...") result = self.getEvernote().removeNotebook(guid=notebook.guid) if result: out.successMessage("Notebook successfully removed.") else: out.failureMessage("Error: could not remove notebook.") return tools.exitErr()