Пример #1
0
    def settings(self, editor=None):
        storage = self.getStorage()
        if editor:
            if editor == '#GET#':
                editor = storage.getUserprop('editor')
                if not editor:
                    editor = config.DEF_WIN_EDITOR if sys.platform == 'win32' else config.DEF_UNIX_EDITOR
                out.successMessage("Current editor is: %s" % editor)
            else:
                storage.setUserprop('editor', editor)
                out.successMessage("Changes have been saved.")
        else:
            settings = ('Geeknote',
                        '*' * 30,
                        'Version: %s' % config.VERSION,
                        'App dir: %s' % config.APP_DIR,
                        'Error log: %s' % config.ERROR_LOG,
                        'Current editor: %s' % storage.getUserprop('editor'))

            user_settings = storage.getUserprops()

            if user_settings:
                user = user_settings[1]['info']
                settings += ('*' * 30,
                             'Username: %s' % user.username,
                             'Id: %s' % user.id,
                             'Email: %s' % user.email)

            out.printLine('\n'.join(settings))
Пример #2
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 = config.DEF_FINDLIMIT
        else:
            count = int(count)
        #print "Search count: %s", count
        logging.debug("Search count: %s", count)

        createFilter = True if search == "*" else False
        result = self.getEvernote().findNotes(request, count, createFilter)
        totalNotes = result.totalNotes
        notes = result.notes

        while len(notes)<totalNotes:
            r = self.getEvernote().findNotes(request, count, createFilter, fromindex = len(notes))
            notes = notes + r.notes

        if result.totalNotes == 0:
            out.successMessage("Notes have not been found.")

        # save search result
        # print result
        self.getStorage().setSearch(result)

        out.SearchResult(notes, request, showUrl=with_url)
Пример #3
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.successMessage("Notes have not been found.")
                return tools.exit()

            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
Пример #4
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()
Пример #5
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()
Пример #6
0
    def settings(self, editor=None):
        storage = self.getStorage()
        if editor:
            if editor == "#GET#":
                editor = storage.getUserprop("editor")
                if not editor:
                    editor = config.DEF_WIN_EDITOR if sys.platform == "win32" else config.DEF_UNIX_EDITOR
                out.successMessage("Current editor is: %s" % editor)
            else:
                storage.setUserprop("editor", editor)
                out.successMessage("Changes have been saved.")
        else:
            settings = (
                "Geeknote",
                "*" * 30,
                "Version: %s" % config.VERSION,
                "App dir: %s" % config.APP_DIR,
                "Error log: %s" % config.ERROR_LOG,
                "Current editor: %s" % storage.getUserprop("editor"),
            )

            user_settings = storage.getUserprops()

            if user_settings:
                user = user_settings[1]["info"]
                settings += ("*" * 30, "Username: %s" % user.username, "Id: %s" % user.id, "Email: %s" % user.email)

            out.printLine("\n".join(settings))
Пример #7
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.successMessage("Notes have not been found.")

        # save search result
        # print result
        self.getStorage().setSearch(result)

        out.SearchResult(result.notes, request, showUrl=with_url)
Пример #8
0
 def changSetting(self, key, value, defaultValue):
     oldValue = value
     if value == '#GET#':
         oldValue = self.getStorage().getUserprop(key) if self.getStorage().getUserprop(key) else defaultValue
     else:
         self.getStorage().setUserprop(key, value)
         out.successMessage("Changes have been saved.")
     out.successMessage("Current %s is: %s " % (key, oldValue))
Пример #9
0
 def settings(self, editor=None):
     if editor:
         if editor == '#GET#':
             editor = self.getStorage().getUserprop('editor')
             if not editor:
                 editor = config.DEF_WIN_EDITOR if sys.platform == 'win32' else config.DEF_UNIX_EDITOR
             out.successMessage("Current editor is: %s" % editor)
         else:
             self.getStorage().setUserprop('editor', editor)
             out.successMessage("Changes have been saved.")
Пример #10
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()
Пример #11
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()
Пример #12
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.exit()
Пример #13
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
Пример #14
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
Пример #15
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
Пример #16
0
    def create(self, title):
        self.connectToEvernote()
        out.preloader.setMessage("Creating notebook...")
        result = self.getEvernote().createNotebook(name=title)

        if result:
            out.successMessage("Notebook has been successfully created.")
        else:
            out.failureMessage("Error while the process of creating the notebook.")
            return tools.exit()

        return result
Пример #17
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 has been successfully removed.")
        else:
            out.failureMessage("Error while removing the notebook.")
Пример #18
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 this tag: "%s"?' % tag.name):
            return tools.exit()

        out.preloader.setMessage("Deleting tag...")
        result = self.getEvernote().removeTag(guid=tag.guid)

        if result:
            out.successMessage("Tag has been successfully removed.")
        else:
            out.failureMessage("Error while removing the tag.")
Пример #19
0
    def create(self, title, content, tags=None, notebook=None):

        self.connectToEvertone()

        inputData = self._parceInput(title, content, tags, notebook)

        out.preloader.setMessage("Creating note...")
        result = self.getEvernote().createNote(**inputData)

        if result:
            out.successMessage("Note has been successfully created.")
        else:
            out.failureMessage("Error while creating the note.")
Пример #20
0
    def loadNotes(self, notebook):
        """ Loading all notes of a notebook for backup purpose """
        result = self.findNotes(False, 25, notebookGuid=notebook.guid)
        if result.totalNotes == 0:
            out.successMessage("Notes have not been found.")
        if result.totalNotes > 250:
            out.successMessage("More than 250 notes ! '%s'" % result.totalNotes)
            # FIXME : if more than 250 notes

        # save search result
        # print result
        self.getStorage().setSearch(result)

        return result.notes
Пример #21
0
    def edit(self, note, title=None, content=None, tags=None, notebook=None):

        self.connectToEvertone()
        note = self._searchNote(note)

        inputData = self._parceInput(title, content, tags, notebook, note)

        out.preloader.setMessage("Saving note...")
        result = self.getEvernote().updateNote(guid=note.guid, **inputData)

        if result:
            out.successMessage("Note has been successfully saved.")
        else:
            out.failureMessage("Error while saving the note.")
Пример #22
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()
Пример #23
0
    def remove(self, note, force=None):

        self.connectToEvertone()
        note = self._searchNote(note)

        if not force and not out.confirm('Are you sure you want to delete this note: "%s"?' % note.title):
            return tools.exit()

        out.preloader.setMessage("Deleting note...")
        result = self.getEvernote().removeNote(note.guid)

        if result:
            out.successMessage("Note has been successful deleted.")
        else:
            out.failureMessage("Error while deleting the note.")
Пример #24
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()
Пример #25
0
    def loadNotes(self, notebook):
        """ Loading all notes of a notebook for backup purpose """
        result = self.findNotes(False, 25, notebookGuid=notebook.guid)
        if result.totalNotes == 0:
            out.successMessage("Notes have not been found.")
        if result.totalNotes > 250:
            out.successMessage("More than 250 notes ! '%s'" %
                               result.totalNotes)
            # FIXME : if more than 250 notes

        # save search result
        # print result
        self.getStorage().setSearch(result)

        return result.notes
Пример #26
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 has been successfully removed.")
        else:
            out.failureMessage("Error while removing the notebook.")
Пример #27
0
    def remove(self, note, force=None):

        self.connectToEvertone()
        note = self._searchNote(note)

        if not force and not out.confirm('Are you sure you want to delete this note: "%s"?' % note.title):
            return tools.exit()

        out.preloader.setMessage("Deleting note...")
        result = self.getEvernote().removeNote(note.guid)

        if result:
            out.successMessage("Note has been successful deleted.")
        else:
            out.failureMessage("Error while deleting the note.")
Пример #28
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)

        # Reduces the count by the amount of notes already retrieved
        update_count = lambda c: max(c - len(result.notes), 0)

        count = update_count(count)

        # Evernote api will only return so many notes in one go. Checks for more
        # notes to come whilst obeying count rules
        while ((result.totalNotes != len(result.notes)) and count != 0):
            offset = len(result.notes)
            result.notes += self.getEvernote().findNotes(
                request, count, createFilter, offset).notes
            count = update_count(count)

        if result.totalNotes == 0:
            out.successMessage("Notes have not been found.")

        # save search result
        # print result
        self.getStorage().setSearch(result)

        out.SearchResult(result.notes, request, showUrl=with_url)
Пример #29
0
    def edit(self, note, title=None, content=None, tag=None, created=None, notebook=None, resource=None, reminder=None, raw=None):
        self.connectToEvernote()
        note = self._searchNote(note)

        inputData = self._parseInput(title, content, tag, created, notebook, resource, note, reminder=reminder)

        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()
Пример #30
0
    def edit(self, note, title=None, content=None, tags=None, notebook=None, resource=None):

        self.connectToEvertone()
        note = self._searchNote(note)

        inputData = self._parseInput(title, content, tags, notebook, resource, note)

        if inputData['content'] == config.EDITOR_OPEN:
            result = self._editWithEditorInThread(inputData, note)
        else:
            out.preloader.setMessage("Saving note...")
            result = bool(self.getEvernote().updateNote(guid=note.guid, **inputData))

        if result:
            out.successMessage("Note has been successfully saved.")
        else:
            out.failureMessage("Error while saving the note.")
Пример #31
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)

        # Reduces the count by the amount of notes already retrieved
        update_count = lambda c: max(c - len(result.notes), 0)

        count = update_count(count)

        # Evernote api will only return so many notes in one go. Checks for more
        # notes to come whilst obeying count rules
        while (result.totalNotes != len(result.notes)) and count != 0:
            offset = len(result.notes)
            result.notes += self.getEvernote().findNotes(request, count, createFilter, offset).notes
            count = update_count(count)

        if result.totalNotes == 0:
            out.successMessage("Notes have not been found.")

        # save search result
        # print result
        self.getStorage().setSearch(result)

        out.SearchResult(result.notes, request, showUrl=with_url)
Пример #32
0
    def create(self, title, content=None, tags=None, notebook=None, resource=None):

        self.connectToEvertone()

        # Optional Content.
        content = content or " "

        inputData = self._parseInput(title, content, tags, notebook, resource)

        if inputData['content'] == config.EDITOR_OPEN:
            result = self._editWithEditorInThread(inputData)
        else:
            out.preloader.setMessage("Creating note...")
            result = bool(self.getEvernote().createNote(**inputData))

        if result:
            out.successMessage("Note has been successfully created.")
        else:
            out.failureMessage("Error while creating the note.")
Пример #33
0
    def remove(self, note, force=None):
        self.connectToEvernote()
        note = self._searchNote(note)
        if note:
            out.preloader.setMessage("Loading note...")
            self.getEvernote().loadNoteContent(note)
            out.showNote(note, self.getEvernote().getUserInfo().id, self.getEvernote().getUserInfo().shardId)

        if not force and not out.confirm("Are you sure you want to " 'delete this note: "%s"?' % note.title):
            return tools.exit()

        out.preloader.setMessage("Deleting note...")
        result = self.getEvernote().removeNote(note.guid)

        if result:
            out.successMessage("Note successfully deleted.")
        else:
            out.failureMessage("Error: could not delete note.")
            return tools.exitErr()
Пример #34
0
    def create(self, title, content=None, tag=None, created=None, notebook=None, resource=None, reminder=None, raw=None):
        self.connectToEvernote()

        # Optional Content.
        content = content or " "

        inputData = self._parseInput(title, content, tag, created, notebook, resource, reminder=reminder)

        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()
Пример #35
0
    def remove(self, note, force=None):

        self.connectToEvernote()
        note = self._searchNote(note)
        if note:
            out.preloader.setMessage("Loading note...")
            self.getEvernote().loadNoteContent(note)
            out.showNote(note, self.getEvernote().getUserInfo().id, self.getEvernote().getUserInfo().shardId)

        if not force and not out.confirm('Are you sure you want to '
                                         'delete this note: "%s"?' % note.title):
            return tools.exit()

        out.preloader.setMessage("Deleting note...")
        result = self.getEvernote().removeNote(note.guid)

        if result:
            out.successMessage("Note successfully deleted.")
        else:
            out.failureMessage("Error: could not delete note.")
            return tools.exitErr()
Пример #36
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.successMessage("Notes have not been found.")

        # save search result
        # print result
        self.getStorage().setSearch(result)

        out.SearchResult(result.notes, request, showUrl=with_url)
Пример #37
0
    def imgupload(self, title, img, description):

        self.connectToEvernote()

	filedata = open( img, 'rb').read()
	md5 = hashlib.md5()
	md5.update(filedata)
	hashHex = md5.hexdigest()
 
  	data = Types.Data()
	data.size = len(filedata)
	data.bodyHash = hashHex
	data.body = filedata
 
	resource = Types.Resource()
	resource.data = data
 
	content = '<?xml version="1.0" encoding="UTF-8"?>'
 	content += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd">'
	content += '<en-note>'
	content += '<en-media type="image/jpeg" hash="' + hashHex + '"/>'
	content += '<p>' + description + '</p>'
	content += '</en-note>'

        enmlText = {
            "title": title,
            "content": content,
            "resource": resource,
        }
        enmlText = tools.strip(enmlText)
		
	result = self.getEvernote().createImgNote(**enmlText)

	if result:
     		out.successMessage("Note has been successfully created.")
	else:
		out.failureMessage("Error while creating the note.")
Пример #38
0
 def settings(self, editor=None, suffix=None):
     if editor:
         if editor == '#GET#':
             editor = self.getStorage().getUserprop('editor')
             if not editor:
                 editor = config.DEF_WIN_EDITOR if sys.platform == 'win32' else config.DEF_UNIX_EDITOR
             out.successMessage("Current editor is: %s" % editor)
         else:
             self.getStorage().setUserprop('editor', editor)
             out.successMessage("Changes have been saved.")
     if suffix:
         if suffix == '#GET#':
             suffix = self.getStorage().getUserprop('suffix')
             out.successMessage("Current suffix is: %s" % suffix)
         else:
             self.getStorage().setUserprop('suffix', suffix)
             out.successMessage("Changes have been saved.")
Пример #39
0
    def settings(self, editor=None, extras=None, note_ext=None):
        storage = self.getStorage()

        if editor:
            if editor == '#GET#':
                editor = storage.getUserprop('editor')
                if not editor:
                    editor = os.environ.get("editor")
                if not editor:
                    editor = os.environ.get("EDITOR")
                if not editor:
                    editor = config.DEF_WIN_EDITOR if sys.platform == 'win32' else config.DEF_UNIX_EDITOR
                out.successMessage("Current editor is: %s" % editor)
            else:
                storage.setUserprop('editor', editor)
                out.successMessage("Changes have been saved.")
        if note_ext:
            if note_ext == '#GET#':
                note_ext = storage.getUserprop('note_ext')
                if not note_ext or not storage.getUserprop('note_ext'):
                    note_ext = config.DEF_NOTE_EXT
                out.successMessage("Default note extension is: %s" % note_ext)
            else:
                storage.setUserprop('note_ext', note_ext)
                out.successMessage("Changes have been saved.")

        if all([not editor, not note_ext]):
            settings = ('Geeknote',
                        '*' * 30,
                        'Version: %s' % config.VERSION,
                        'App dir: %s' % config.APP_DIR,
                        'Error log: %s' % config.ERROR_LOG,
                        'Current editor: %s' % storage.getUserprop('editor'),
                        'Note extension: %s' % storage.getUserprop('note_ext'))

            user_settings = storage.getUserprops()

            if user_settings:
                user = user_settings[1]['info']
                settings += ('*' * 30,
                             'Username: %s' % user.username,
                             'Id: %s' % user.id,
                             'Email: %s' % user.email)

            out.printLine('\n'.join(settings))
Пример #40
0
    def settings(self, editor=None, extras=None):
        storage = self.getStorage()
        if editor:
            if editor == '#GET#':
                editor = storage.getUserprop('editor')
                if not editor:
                    editor = config.DEF_WIN_EDITOR if sys.platform == 'win32' else config.DEF_UNIX_EDITOR
                out.successMessage("Current editor is: %s" % editor)
            else:
                storage.setUserprop('editor', editor)
                out.successMessage("Changes have been saved.")
        elif extras:
            if extras == '#GET#':
                extras = storage.getUserprop('markdown2_extras')
                if not extras:
                    extras = None
                out.successMessage("Current markdown2 extras is : %s" % extras)
            else:
                storage.setUserprop('markdown2_extras', extras.split(','))
                out.successMessage("Changes have been saved.")
        else:
            settings = ('Geeknote', '*' * 30, 'Version: %s' % config.VERSION,
                        'App dir: %s' % config.APP_DIR,
                        'Error log: %s' % config.ERROR_LOG,
                        'Current editor: %s' % storage.getUserprop('editor'),
                        'Markdown2 Extras: %s' %
                        ','.join(storage.getUserprop('markdown2_extras')))

            user_settings = storage.getUserprops()

            if user_settings:
                user = user_settings[1]['info']
                settings += ('*' * 30, 'Username: %s' % user.username,
                             'Id: %s' % user.id, 'Email: %s' % user.email)

            out.printLine('\n'.join(settings))
Пример #41
0
def main(args=None):
    try:
        exit_status_code = 0

        sys_argv = sys.argv[1:]
        if isinstance(args, list):
            sys_argv = args

        sys_argv = tools.decodeArgs(sys_argv)

        notebook = sys_argv[0] if len(sys_argv) >= 1 else None

        if not notebook:
            return tools.exit()

        evernote = geeknote.GeekNoteConnector().getEvernote()
        store = None
        nb = None
        shareToken = evernote.authToken

        localNotebooks = evernote.findNotebooks()

        for key, item in enumerate(localNotebooks):
            if item.name == notebook:
                nb = item
                store = evernote.getNoteStore()

        if not store:
            linkedNotebooks = evernote.findLinkedNotebooks()

            for key, item in enumerate(linkedNotebooks):
                if item.shareName == notebook:
                    nb = item
                    store = evernote.getNoteStoreByUrl(item.noteStoreUrl)
                    auth = store.authenticateToSharedNotebook(item.shareKey, evernote.authToken)
                    shareToken = auth.authenticationToken

                    nb = store.getSharedNotebookByAuth(shareToken)

                    break

        tags = store.listTagsByNotebook(shareToken, nb.notebookGuid)

        tagsMap = {}

        for key, item in enumerate(tags):
            tagsMap[item.guid] = item.name

        updatedFilter = NoteTypes.NoteFilter()
        offset = 0
        maxNotes = 40000
        resultSpec = NoteTypes.NotesMetadataResultSpec(includeCreated=True, includeUpdated=True, includeTitle=True, includeAttributes=True, includeTagGuids=True)

        notesMetadata = store.findNotesMetadata(shareToken, updatedFilter, offset, maxNotes, resultSpec)

        for key, item in enumerate(notesMetadata.notes):
            note = store.getNote(shareToken, item.guid, withContent=True, withResourcesData=True, withResourcesRecognition=False, withResourcesAlternateData=False)
            slug = note.attributes.sourceURL if note.attributes.sourceURL else note.guid

            if note.resources:
                for key, res in enumerate(note.resources):
                    if res.mime in config.DUMP_RESOURCE_MIME_PATH:
                        if not res.attributes.fileName:
                            res.attributes.fileName = "%s.%s" % (res.guid, re.sub(r'[^/]+/', '', res.mime))

                        resPath = "%s/%s" % (config.DUMP_RESOURCE_MIME_PATH[res.mime], res.attributes.fileName)

                        with open(resPath, "wb") as resWriter:
                            resWriter.write(res.data.body)

            with io.open("%s/%s.xml" % (config.DUMP_PATH, slug.replace("/", "-")), "w", encoding="utf-8") as noteWriter:
                noteWriter.write(u'<?xml version="1.0" ?>\n')
                noteWriter.write(u"<note>\n")

                noteWriter.write(u"\t<tags>\n")
                for key, tag in enumerate(note.tagGuids):
                    noteWriter.write(u"\t\t<tag>%s</tag>\n" % tagsMap[tag].decode('utf-8'))

                noteWriter.write(u"\t</tags>\n")
                noteWriter.write(u"\t<author>%s</author>\n" % note.attributes.author.decode('utf-8'))
                noteWriter.write(u"\t<title>%s</title>\n" % note.title.decode('utf-8'))

                if note.attributes.lastEditedBy:
                    noteWriter.write(u"\t<lastEditedBy>%s</lastEditedBy>\n" % note.attributes.lastEditedBy.decode('utf-8'))

                if note.resources:
                    noteWriter.write(u"\t<resources>\n")
                    for key, res in enumerate(note.resources):
                        resHash = ''.join(x.encode('hex') for x in res.data.bodyHash)
                        noteWriter.write(('\t\t<resource hash="%s" path="%s/%s"/>\n' % (resHash, config.DUMP_RESOURCE_MIME_PATH[res.mime], res.attributes.fileName)).decode('utf-8'))
                    noteWriter.write(u"\t</resources>\n")

                noteWriter.write(u"\t<content>%s</content>\n" % re.sub(r'\<[?!][^>]+\>', "", note.content.decode('utf-8')))
                noteWriter.write(u"</note>")

        out.successMessage("Done.")
    except (KeyboardInterrupt, SystemExit, tools.ExitException), e:
        if e.message:
            exit_status_code = e.message
Пример #42
0
    def dedup(self, notebook=None):
        logging.debug("Retrieving note metadata")

        request = self._createSearchRequest(None, None, notebook, None, None,
                                            None)
        logging.debug(request)
        evernote = self.getEvernote()
        out.preloader.setMessage("Retrieving metadata...")
        result = evernote.findNotes(request, EDAM_USER_NOTES_MAX, False, 0)
        notes = result.notes

        logging.debug("First pass, comparing metadata of " +
                      str(len(result.notes)) + " notes")
        notes_dict = {}

        for note in notes:
            # Use note title, contentLength and resource descriptors
            # as the best "unique" key we can make out of the metadata.
            # Anything more unique requires us to inspect the content,
            # which we try to avoid since it requires a per-note API call.
            # This will create false positives, which we resolve in another pass,
            # actually inspecting note content of a hopefully smaller
            # set of potential duplicates.
            noteId = note.title + " (" + str(
                note.contentLength) + ") with " + str(
                    note.largestResourceMime) + " (" + str(
                        note.largestResourceSize) + ")"
            if noteId in notes_dict:
                notes_dict[noteId].append(note)
                logging.debug(" note:  " + noteId + "\" with guid " +
                              note.guid + " potentially duplicated " +
                              str(len(notes_dict[noteId])))
            else:
                notes_dict[noteId] = [note]


#                logging.debug(" note:  " + noteId
#                              + "\" with guid " + note.guid)

        all_dups = [
            dups for id, dups in notes_dict.iteritems() if len(dups) > 1
        ]  # list of lists
        total_dups = sum(map(len, all_dups))  # count total

        logging.debug("Second pass, testing content among " +
                      str(len(all_dups)) + " groups, " + str(total_dups) +
                      " notes")
        notes_dict = {}
        for dup_group in all_dups:
            for note in dup_group:
                out.preloader.setMessage("Retrieving content...")
                self.getEvernote().loadNoteContent(note)
                md5 = hashlib.md5()
                md5.update(note.content)
                noteHash = md5.hexdigest()
                noteId = md5.hexdigest() + " " + note.title
                if noteId in notes_dict:
                    notes_dict[noteId].append(note)
                    logging.debug("duplicate \"" + noteId + "\" with guid " +
                                  note.guid + ", duplicated " +
                                  str(len(notes_dict[noteId])))
                else:
                    notes_dict[noteId] = [note]
                    logging.debug("new note  \"" + noteId + "\" with guid " +
                                  note.guid)

        all_dups = [
            dups for id, dups in notes_dict.iteritems() if len(dups) > 1
        ]  # list of lists
        total_dups = sum(map(len, all_dups))  # count total

        logging.debug("Third pass, deleting " + str(len(all_dups)) +
                      " groups, " + str(total_dups) + " notes")
        removed_count = 0
        for dup_group in all_dups:
            dup_group.pop()  # spare the last one, delete the rest
            for note in dup_group:
                removed_count += 1
                logging.debug("Deleting \"" + note.title + "\" created " +
                              out.printDate(note.created) + " with guid " +
                              note.guid + " (" + str(removed_count) + "/" +
                              str(total_dups) + ")")
                out.preloader.setMessage("Removing note...")
                evernote.removeNote(note.guid)

        out.successMessage("Removed " + str(removed_count) +
                           " duplicates within " + str(len(result.notes)) +
                           " total notes")
Пример #43
0
    def settings(self, editor=None, extras=None, note_ext=None):
        storage = self.getStorage()

        if editor:
            if editor == '#GET#':
                out.successMessage("Current editor is: %s" %
                                   getEditor(storage))
            else:
                storage.setUserprop('editor', editor)
                out.successMessage("Changes saved.")
        if extras:
            if extras == '#GET#':
                out.successMessage("Current markdown2 extras is : %s" %
                                   getExtras(storage))
            else:
                storage.setUserprop('markdown2_extras', extras.split(','))
                out.successMessage("Changes saved.")
        if note_ext:
            if note_ext == '#GET#':
                out.successMessage("Default note extension is: %s" %
                                   getNoteExt(storage))
            else:
                if len(note_ext.split(',')) == 2:
                    storage.setUserprop('note_ext', note_ext.replace(" ", ""))
                    out.successMessage("Changes saved.")
                else:
                    out.failureMessage(
                        "Error in note extension, format is '.markdown, .org'")

        if all([not editor, not extras, not note_ext]):
            editor = getEditor(storage)
            extras = getExtras(storage)
            note_ext = getNoteExt(storage)
            settings = ('Geeknote', '*' * 30, 'Version: %s' % __version__,
                        'App dir: %s' % config.APP_DIR,
                        'Error log: %s' % config.ERROR_LOG,
                        'Current editor: %s' % editor, 'Markdown2 Extras: %s' %
                        (extras if extras is None else ','.join(extras)),
                        'Note extension: %s' % note_ext)

            user_settings = storage.getUserprops()

            if user_settings:
                user = user_settings[1]['info']
                settings += ('*' * 30, 'Username: %s' % user.username,
                             'Id: %s' % user.id, 'Email: %s' % user.email)

            out.printLine('\n'.join(settings))