Пример #1
0
        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()
Пример #2
0
        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()
Пример #3
0
    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)
Пример #4
0
    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)
Пример #5
0
    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
Пример #6
0
    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()
Пример #7
0
    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
Пример #8
0
    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()
Пример #9
0
    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")
Пример #10
0
    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()
Пример #11
0
 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()
Пример #12
0
    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)
Пример #13
0
    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()
Пример #14
0
    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()
Пример #15
0
    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
Пример #16
0
    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()
Пример #17
0
    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()
Пример #18
0
    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)
Пример #19
0
    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)
Пример #20
0
    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()
Пример #21
0
    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()
Пример #22
0
    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()
Пример #23
0
    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
Пример #24
0
    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")
Пример #25
0
    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)
Пример #26
0
    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']
Пример #27
0
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)
Пример #28
0
    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)
Пример #29
0
    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)
Пример #30
0
    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']
Пример #31
0
    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()
Пример #32
0
    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()
Пример #33
0
    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
        )
Пример #34
0
    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
Пример #35
0
    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
Пример #36
0
    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")
Пример #37
0
    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
Пример #38
0
    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")
Пример #39
0
    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
Пример #40
0
    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()
Пример #41
0
    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
Пример #42
0
        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()
Пример #43
0
    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()
Пример #44
0
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)
Пример #45
0
    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()
Пример #46
0
    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()
Пример #47
0
    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()
Пример #48
0
    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")
Пример #49
0
 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))
Пример #50
0
    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()