Esempio n. 1
0
    def _create_remote_note(self, note_title, note_guid):
        """Create remote note"""
        remote_note = ttypes.Note(
            title=note_title,
            guid=note_guid,
            content='<en-note></en-note>',
            notebookGuid=self.notebook.guid,
            attributes=ttypes.NoteAttributes(),
            updated=1,
            resources=[
                ttypes.Resource(
                    guid='file',
                    mime='text',
                    attributes=ttypes.ResourceAttributes(fileName='file', ),
                    data=ttypes.Data(
                        body='',
                        bodyHash='',
                    ),
                )
            ],
        )

        search_result = MagicMock()
        search_result.totalNotes = 1
        search_result.startIndex = 0
        search_result.notes = [remote_note]
        self.note_store.findNotes.return_value = search_result
        self.note_store.getNote.return_value = remote_note

        return remote_note
Esempio n. 2
0
def add_img(note, image_path):
    # To include an attachment such as an image in a note, first create a Resource
    # for the attachment. At a minimum, the Resource contains the binary attachment
    # data, an MD5 hash of the binary data, and the attachment MIME type.
    # It can also include attributes such as filename and location.
    # image_path = constants_path = os.path.join(os.path.dirname(__file__), "enlogo.png")
    image_path = 'photos/' + image_path
    with open(image_path, 'rb') as image_file:
        image = image_file.read()
    md5 = hashlib.md5()
    md5.update(image)
    hash = md5.digest()

    data = Types.Data()
    data.size = len(image)
    data.bodyHash = hash
    data.body = image

    resource = Types.Resource()
    resource.mime = 'image/png'
    resource.data = data

    # Now, add the new Resource to the note's list of resources
    note.resources.append(resource)
    print(len(note.resources))
    # To display the Resource as part of the note's content, include an <en-media>
    # tag in the note's ENML content. The en-media tag identifies the corresponding
    # Resource using the MD5 hash.
    hash_hex = binascii.hexlify(hash)
    hash_str = hash_hex.decode("UTF-8")
    content = '<br/>'
    content += '<en-media type="image/png" hash="{}"/>'.format(hash_str)
    content += '<br/>'
    return content
Esempio n. 3
0
def create_new_note(file_path, mime):
    # import pdb; pdb.set_trace()
    file_name = os.path.basename(file_path)
    file_cont = open(file_path, "rb").read()
    md5 = hashlib.md5()
    md5.update(file_cont)
    hash = md5.digest()
    
    data = Types.Data()
    data.size = len(file_cont)
    data.bodyHash = hash
    data.body = file_cont

    attr = Types.ResourceAttributes()
    attr.fileName = file_name

    resource = Types.Resource()
    resource.mime = mime
    resource.data = data
    resource.attributes = attr

    note = Types.Note()
    note.title = file_name
    note.resources = [resource]
    note.notebookGuid = notebook_id
    note.content = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
<en-note>
<ul>
<li></li>
</ul>
<hr/>
<en-media type="%(mime)s" hash="%(hash)s" />
</en-note>""" % {"mime":mime, "hash":binascii.hexlify(hash)}
    note_store.createNote(auth_token, note)
Esempio n. 4
0
def add_jpeg(note, jpeg_bytesio):
    '''Add jpeg  attachment to evernote note from BytesIo object'''
    image = jpeg_bytesio.getvalue()
    md5 = hashlib.md5()
    md5.update(image)
    hash = md5.digest()

    data = Types.Data()
    data.size = len(image)
    data.bodyHash = hash
    data.body = image

    resource = Types.Resource()
    resource.mime = 'image/jpeg'
    resource.data = data

    # Now, add the new Resource to the note's list of resources
    note.resources = [resource]
    # To display the Resource as part of the note's content, include an <en-media>
    # tag in the note's ENML content. The en-media tag identifies the corresponding
    # Resource using the MD5 hash.

    # The content of an Evernote note is represented using Evernote Markup Language
    # (ENML). The full ENML specification can be found in the Evernote API Overview
    # at http://dev.evernote.com/documentation/cloud/chapters/ENML.php
    hash_hex = binascii.hexlify(hash)
    hash_str = hash_hex.decode("UTF-8")
    note.content += '<en-media type="image/png" hash="{}"/>'.format(hash_str)
    return note
Esempio n. 5
0
 def test_remote_resources(self):
     """Test syncing remote resources"""
     remote = self._create_remote_note(
         resources=[ttypes.Resource(
             data=ttypes.Data(body=open(resource_path).read()),
             mime='image/png',
             attributes=ttypes.ResourceAttributes(
                 fileName='test.png',
             )
         )],
     )
     self.sync.notes_remote()
     resource = self.sq(Note).filter(
         Note.guid == remote.guid,
     ).one().resources[0]
     self.assertEqual(
         'test.png', resource.file_name,
     )
     remote.resources = None
     self.note_store.updateNote(self.auth_token, remote)
     self.sync.notes_remote()
     with self.assertRaises(NoResultFound):
         # fetch synchronized not very genius, but we don't need that
         get_db_session().query(Resource).filter(
             Resource.guid == resource.guid,
         ).one()
Esempio n. 6
0
 def create_note(self, noteFullPath, content=None, fileDir=None):
     if self.get(noteFullPath): return False
     if '/' in noteFullPath:
         notebook = noteFullPath.split('/')[0]
         title = noteFullPath.split('/')[1]
     else:
         notebook = self.storage.defaultNotebook
         title = noteFullPath
     note = Types.Note()
     note.title = title
     note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
     note.content += '<en-note>'
     note.content += content or ''
     if self.get(notebook) is None: self.create_notebook(notebook)
     note.notebookGuid = self.get(notebook).guid
     if not fileDir is None:
         with open(fileDir, 'rb') as f: fileBytes = f.read()
         fileData = Types.Data()
         fileData.bodyHash = self._md5(fileBytes)
         fileData.size = len(fileBytes)
         fileData.body = fileBytes
         fileAttr = Types.ResourceAttributes()
         fileAttr.fileName = title + '.md'
         fileAttr.attachment = True
         fileResource = Types.Resource()
         fileResource.data = fileData
         fileResource.mime = 'application/octet-stream'
         fileResource.attributes = fileAttr
         note.resources = [fileResource]
         note.content += '<en-media type="application/octet-stream" hash="%s"/>' % fileData.bodyHash
     note.content += '</en-note>'
     note = self.noteStore.createNote(note)
     self.storage.create_note(note, notebook)
     return True
Esempio n. 7
0
def create_en_resource(file_list):
    resource_list = []
    for filename in file_list:
        # Calculate the md5 hash of the pdf
        md5 = hashlib.md5()
        with open(filename, "rb") as imageFile:
            file_bytes = imageFile.read()
        md5.update(file_bytes)
        md5hash = md5.hexdigest()

        # Create the Data type for evernote that goes into a resource
        file_data = Types.Data()
        file_data.bodyHash = md5hash
        file_data.size = len(file_bytes)
        file_data.body = file_bytes

        # Create a resource for the note that contains the pdf
        file_resource = Types.Resource()
        file_resource.data = file_data
        file_resource.mime = "image/" + os.path.basename(filename).split(
            ".")[1]

        # Create a resource list to hold the pdf resource
        resource_list.append(file_resource)
    return resource_list
Esempio n. 8
0
        def make_resource(filename):
            try:
                mtype = mimetypes.guess_type(filename)[0]
                    
                if mtype.split('/')[0] == "text":
                    rmode = "r"
                else:
                    rmode = "rb"

                with open(filename, rmode) as f:
                    """ file exists """
                    resource = Types.Resource()
                    resource.data = Types.Data()

                    data = f.read()
                    md5 = hashlib.md5()
                    md5.update(data)
                    
                    resource.data.bodyHash = md5.hexdigest() 
                    resource.data.body = data
                    resource.data.size = len(data) 
                    resource.mime = mtype
                    resource.attributes = Types.ResourceAttributes()
                    resource.attributes.fileName = os.path.basename(filename)
                    return resource
            except IOError:
                msg = "The file '%s' does not exist." % filename
                out.failureMessage(msg)
                raise IOError(msg)
    def _get_resource(self, attach):
        '''
        To display the Resource as part of the note's content, 
        include an <en-media> tag in the note's ENML content. 
        The en-media tag identifies the corresponding
        Resource using the MD5 hash.
        '''
        md5 = hashlib.md5()
        md5.update(attach)
        hash = md5.digest()
        hashHex = binascii.hexlify(hash)
        '''
        To include an attachment such as an image in a note, 
        first create a Resource for the attachment. 
        At a minimum, the Resource contains the binary attachment data, 
        an MD5 hash of the binary data, and the attachment MIME type. 
        It can also include attributes such as filename and location.
        '''
        data = Types.Data()
        data.size = len(attach)
        data.bodyHash = hash
        data.body = attach

        resource = Types.Resource()
        resource.mime = 'image/png'
        resource.data = data
        return resource, hashHex
Esempio n. 10
0
 def getSchemaResource(self):
     if not os.path.exists(base_path):
         os.mkdir(base_path)
     if not os.path.exists(base_path + str(self.guid)):
         os.mkdir(base_path + str(self.guid))
     #create knowledge.json
     file_name = base_path + str(self.guid) + '/knowledge.json'
     if not os.path.exists(file_name):
         with open(file_name, 'wb') as f:
             json.dump({}, f)
     #compute hash value
     raw = open(file_name, 'rb').read()
     md5 = hashlib.md5()
     md5.update(raw)
     hash = md5.digest()
     #buid Data
     data = Types.Data()
     data.size = len(raw)
     data.bodyHash = hash
     data.body = raw
     #build attribute
     attr = Types.ResourceAttributes()
     attr.fileName = "knowledge.json"
     attr.clientWillIndex = False
     attr.attachment = True
     #build Resources
     resource = Types.Resource()
     resource.mime = 'text/json'
     resource.data = data
     resource.attributes = attr
     return resource
Esempio n. 11
0
def file2evernote(filename,
                  data,
                  mimetype,
                  notebook=None,
                  tags=[],
                  title=None):
    print("Creating note for file {0} in notebook {1}".format(
        filename, notebook))

    guid = get_notebook_by_name(notebook).guid

    if not title:
        title = filename

    resource = Types.Resource()
    resource.data = Types.Data()
    resource.data.body = data
    resource.attributes = Types.ResourceAttributes(fileName=filename,
                                                   attachment=False)
    resource.mime = mimetype
    hash = hashlib.md5()
    hash.update(resource.data.body)
    attachment = '<en-media type="{0}" hash="{1}" />\n'.format(
        resource.mime, hash.hexdigest())

    content = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
<en-note>""" + attachment + "</en-note>"

    note = Types.Note(title=title,
                      content=content,
                      tagNames=tags,
                      resources=[resource],
                      notebookGuid=guid)
    return noteStore.createNote(note)
Esempio n. 12
0
    def genNewImgRes(oldImgRes, newImgBytes, newMime=None):
        """Generate new image resource

        Args:
            oldImgRes (Resource): old image resource
            newImgBytes (bytes): new image bytes
            newMime (str): new image MIME. Default is None. If None, get from oldImgRes.mime
        Returns:
            new image resouce
        Raises:
        """
        if not newMime:
            newMime = oldImgRes.mime  # 'image/png'

        newMd5Bytes = utils.calcMd5(
            newImgBytes, isRespBytes=True
        )  # b'\xaa\x05r\x15l\xb8\xa9\x9a\xe3\xc3MR2\x08\xa8['

        newLen = len(newImgBytes)

        newData = Types.Data()
        newData.size = newLen
        newData.bodyHash = newMd5Bytes
        newData.body = newImgBytes

        newImgRes = Types.Resource()
        newImgRes.mime = newMime
        newImgRes.data = newData
        newImgRes.attributes = oldImgRes.attributes

        return newImgRes
Esempio n. 13
0
def EvernoteAddNote(notedata):
    # To create a new note, simply create a new Note object and fill in
    # attributes such as the note's title.
    note = Types.Note()
    #note.title = "Test note from EDAMTest.py"
    note.title = notedata["Title"]

    note.content = '<?xml version="1.0" encoding="UTF-8"?>'
    note.content += '<!DOCTYPE en-note SYSTEM ' \
                    '"http://xml.evernote.com/pub/enml2.dtd">'
    note.content += '<en-note>%s<br/>' % notedata["Content"]

    # To include an attachment such as an image in a note, first create a Resource
    # for the attachment. At a minimum, the Resource contains the binary attachment
    # data, an MD5 hash of the binary data, and the attachment MIME type.
    # It can also include attributes such as filename and location.
    for root, dirs, files in os.walk(notedata["PicPath"], False):
        print("Root = ", root, "dirs = ", dirs, "files = ", files)
    for file in files:
        image_path=root+"/"+file
        print("image_path:" + str(image_path))
        with open(image_path, 'rb') as image_file:
            image = image_file.read()
        md5 = hashlib.md5()
        md5.update(image)
        hash = md5.digest()

        data = Types.Data()
        data.size = len(image)
        data.bodyHash = hash
        data.body = image

        resource = Types.Resource()
        resource.mime = 'image/jpg'
        resource.data = data

        # Now, add the new Resource to the note's list of resources
        note.resources = [resource]
        
        # To display the Resource as part of the note's content, include an <en-media>
        # tag in the note's ENML content. The en-media tag identifies the corresponding
        # Resource using the MD5 hash.
        hash_hex = binascii.hexlify(hash)
        hash_str = hash_hex.decode("UTF-8")
        
        # The content of an Evernote note is represented using Evernote Markup Language
        # (ENML). The full ENML specification can be found in the Evernote API Overview
        # at http://dev.evernote.com/documentation/cloud/chapters/ENML.php
        
        note.content += '<en-media type="image/jpg" hash="{}"/>'.format(hash_str)
    note.content += '</en-note>'

    # Finally, send the new note to Evernote using the createNote method
    # The new Note object that is returned will contain server-generated
    # attributes such as the new note's unique GUID.
    created_note = note_store.createNote(note)

    print("Successfully created a new note with GUID: ", created_note.guid)
Esempio n. 14
0
 def open_note(self, guid, insert_in_content=True, filename=None, prompt=False, **unk_args):
     import hashlib, mimetypes
     if filename is None:
         view = self.view
         if view is None:
             sublime.error_message("Evernote plugin could not open the file you specified!")
             return
         filename = view.file_name() or ""
         contents = view.substr(sublime.Region(0, view.size())).encode('utf8')
     else:
         filename = os.path.abspath(filename)
         if prompt:
             self.window.show_input_panel(
                 "Filename of attachment: ", filename,
                 lambda x: self.open_note(guid, insert_in_content, filename, prompt=False, **unk_args),
                 None, None)
             return
         try:
             with open(filename, 'rb') as content_file:
                 contents = content_file.read()
         except Exception as e:
             sublime.error_message("Evernote plugin could not open the file you specified!")
             print(e)
             return
     try:
         noteStore = self.get_note_store()
         note = noteStore.getNote(self.token(), guid, True, False, False, False)
         mime = mimetypes.guess_type(filename)[0]
         LOG(mime)
         h = hashlib.md5(contents)
         if not isinstance(mime, str):
             mime = "text/plain"
         attachment = Types.Resource(
             # noteGuid=guid,
             mime=mime,
             data=Types.Data(body=contents, size=len(contents), bodyHash=h.digest()),
             attributes=Types.ResourceAttributes(
                 fileName=os.path.basename(filename),
                 attachment=True))
         resources = note.resources or []
         resources.append(attachment)
         if insert_in_content and note.content.endswith("</en-note>"):  # just a precaution
             builtin = note.content.find(SUBLIME_EVERNOTE_COMMENT_BEG, 0, 150)
             if builtin >= 0:
                 builtin_end = note.content.find(SUBLIME_EVERNOTE_COMMENT_END, builtin)
                 content = note.content[0:builtin]+note.content[builtin_end+len(SUBLIME_EVERNOTE_COMMENT_END)+1:]
             else:
                 content = note.content
             note.content = content[0:-10] + \
                 '<en-media type="%s" hash="%s"/></en-note>' % (mime, h.hexdigest())
         note.resources = resources
         def do():
             noteStore.updateNote(self.token(), note)
             self.message("Successfully attached to note '%s'" % note.title)
         async_do(do, "Uploading attachment")
     except Exception as e:
         sublime.error_message(explain_error(e))
Esempio n. 15
0
 def clone_resource(self, resource):
     """Return a cloned Resource instance from given resource instance."""
     data = copy.deepcopy(resource.data)
     if not data.body:
         logger.info(u'Fetching resource data for cloning')
         data.body = self._get_resource_data(resource.guid)
     return Types.Resource(
         data=data, mime=resource.mime, attributes=
         Types.ResourceAttributes(fileName=resource.attributes.fileName))
Esempio n. 16
0
    def create_note(self,
                    auth_token,
                    text,
                    title=None,
                    files=None,
                    notebook_guid=None):
        if files is None:
            files = []
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        # user_store = sdk.get_user_store()
        note_store = sdk.get_note_store()
        note = Types.Note()
        note.title = title or ('%s...' % text[:25] if len(text) > 30 else text)
        if notebook_guid is not None:
            note.notebookGuid = notebook_guid

        attachments = []
        for filename, mime_type in files:
            with open(filename, 'rb') as f:
                data_bytes = f.read()
                md5 = hashlib.md5()
                md5.update(data_bytes)

                data = Types.Data()
                data.size = len(data_bytes)
                data.bodyHash = md5.digest()
                data.body = data_bytes

                resource = Types.Resource()
                resource.mime = mime_type
                resource.data = data
                resource.attributes = Types.ResourceAttributes(
                    fileName=basename(filename))

                # Now, add the new Resource to the note's list of resources
                note.resources = [resource]

            attachments.append(
                '<br /><en-media type="%(mime_type)s" hash="%(md5)s" />' % {
                    'mime_type': mime_type,
                    'md5': md5.hexdigest(),
                })

        note.content = '<?xml version="1.0" encoding="UTF-8"?>' \
            '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' \
            '<en-note>%(text)s<br />%(attachments)s</en-note>' % {
                'text': text,
                'attachments': ''.join(attachments),
            }
        try:
            created_note = note_store.createNote(note)
        except Exception as e:
            print(e)
            logging.getLogger().error(traceback.format_exc())
        return created_note.guid
Esempio n. 17
0
    def add_resource(self, filename):
        """
        Adds a resource (image or pdf at this stage) to the note. Adds a new line at the end of the attachment
        :param filename: name of the file to add to the note
        :type filename: string
        :return:
        """
        accepted_mimes = {
            'gif': 'image/gif',
            'jpg': 'image/jpeg',
            'jpeg': 'image/jpeg',
            'png': 'image/png',
            'pdf': 'application/pdf',
            'html': 'text/html'
        }
        # ^these are mime types that can be displayed inline in the client. Also the only type that will be directly
        # downloaded by the downloader. Will need more testing. Others can be added later.
        extention = filename.split('.')[-1]
        mime_type = accepted_mimes[extention]
        try:
            with open(filename, 'rb') as f:
                attachment = f.read()
        except OSError:
            print("Unable to open file")
            return

        # hashing the attachment
        md5 = hashlib.md5()
        md5.update(attachment)
        hashed_resource = md5.digest()
        # adding the attachment as data Type
        data = Types.Data()
        data.size = len(attachment)
        data.bodyHash = hashed_resource
        data.body = attachment
        # adding the data to the note.
        resource = Types.Resource()
        resource.mime = mime_type
        resource.data = data
        resource.attributes = Types.ResourceAttributes()
        resource.attributes.fileName = filename
        # resource.attachment = True

        if not self.note.resources:
            self.note.resources = [resource]
        else:
            self.note.resources += [resource]

        hash_hex = binascii.hexlify(hashed_resource)
        hash_str = hash_hex.decode("UTF-8")

        self.note.content += '<en-media type="{}" hash="{}"/><br/>'.format(
            mime_type, hash_str)
        return
Esempio n. 18
0
    def _create_evernote_note(self, notebook, filename):
        # Create the new note
        note = Types.Note()
        # Chop extension from filename and use it as note title
        note.title = Tools.chop(os.path.basename(filename), self.ext)
        note.notebookGuid = notebook.guid
        note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
        note.content += '<en-note>'
        md_content = self._get_md_content(filename)
        # Get Tag List from YAML Fonter
        tag_list = self._get_tag_list(md_content)
        # Remove YAML Fronter tags
        md_content = self._remove_yaml_fronter(md_content)
        # Read image links from MD
        file_list_in_md = self._get_images_in_md(md_content)

        # TODO: move to method
        file_hash_dict = dict()
        res = list()
        for f in file_list_in_md:
            file_path = os.path.join(self.notes_path, self._url_decode(f))
            with open(file_path, 'rb') as the_file:
                image = the_file.read()
            md5 = hashlib.md5()
            md5.update(image)
            the_hash = md5.digest()

            data = Types.Data()
            data.size = len(image)
            data.bodyHash = the_hash
            data.body = image

            resource = Types.Resource()
            resource.mime = mimetypes.guess_type(file_path)[0]
            resource.data = data
            # Now, add the new Resource to the note's list of resources
            res.append(resource)
            hash_hex = binascii.hexlify(the_hash)
            file_hash_dict.update({f: hash_hex})

        # Replace MD Link with ENML Link
        note.resources = res
        # Add Tag list from YAML
        note.tagNames = tag_list
        for md_link, hash_hex in file_hash_dict.items():
            en_link = '<en-media type="image/png" hash="' + hash_hex + '"/>'
            md_content = self._exhange_image_links(
                md_content, md_link, en_link)

        enml = markdown2.markdown(md_content).encode('utf-8')
        note.content += self.remove_invalid_urls(enml)
        note.content += '</en-note>'
        return note
Esempio n. 19
0
    def add_resources(self, image_url):
        bodybinary = open(image_url, 'rb').read()
        bodyhash = hashlib.md5(bodybinary).hexdigest()
        self.attachment_contents += '<br /><en-media type="%s" hash="%s" />' % ('image/png', bodyhash)

        data = Types.Data()
        data.size = len(bodybinary)
        data.bodyHash = bodyhash
        data.body = b64decode(str(base64.b64encode(bodybinary).decode()))
        resource = Types.Resource()
        resource.mime = 'image/png'
        resource.data = data
        self.resources.append(resource)
Esempio n. 20
0
def make_resource(path, mime):
    body = open(path, 'rb').read()
    md5 = hashlib.md5()
    md5.update(body)
    hash = md5.digest()
    data = Types.Data()
    data.size = len(body)
    data.bodyHash = hash
    data.body = body
    resource = Types.Resource()
    resource.mime = mime
    resource.data = data
    return resource
Esempio n. 21
0
 def _prepare_resources(self, note):
     """Prepare note resources"""
     return map(
         lambda resource: ttypes.Resource(
             noteGuid=note.guid,
             data=ttypes.Data(body=open(resource.file_path).read()),
             mime=resource.mime,
             attributes=ttypes.ResourceAttributes(
                 fileName=resource.file_name.encode('utf8'), ),
         ),
         self.session.query(models.Resource).filter(
             (models.Resource.note_id == note.id)
             & (models.Resource.action != const.ACTION_DELETE)),
     )
Esempio n. 22
0
def getResource(filepath):
    filename = os.path.basename(filepath)
    data = Types.Data()
    data.body = open(filepath, 'r').read()
    data.size = len(data.body)
    data.bodyHash = hashlib.md5(data.body).hexdigest()
    resource = Types.Resource()
    resource.mime = mimetypes.guess_type(filename)[0]
    resource.data = data
    attr = Types.ResourceAttributes()
    attr.fileName = filename
    resource.attributes = attr
    # print('attachment: ' + filename)
    return resource
Esempio n. 23
0
    def tagsMap_creater(self):
        #creat in local
        #tags=self.noteStore.listTags(self.token)
        #f=open('advancedTagsMap.csv','w+')
        #for tag in tags: f.write(str(tag.updateSequenceNum)+','+tag.guid+','+tag.name+','+str(tag.parentGuid)+'\n')
        #f.close()

        #1 prepare resourse:tagmapcsv
        ##create in memory
        tagmapcsv = Types.Resource()
        tagmapcsv.data = Types.Data()
        ##import data.body
        tags = self.noteStore.listTags(self.token)
        tagmapcsv.data.body = ""
        for tag in tags:
            bodyline = str(tag.updateSequenceNum
                           ) + ',' + tag.guid + ',' + tag.name + ',' + str(
                               tag.parentGuid) + '\n'
            tagmapcsv.data.body += bodyline
        ##calculate data.hash: and hexhash
        m2 = hashlib.md5()
        m2.update(tagmapcsv.data.body)
        tagmapcsv.data.bodyHash = m2.digest()
        hexhash = binascii.hexlify(tagmapcsv.data.bodyHash)
        ##set the file
        tagmapcsv.mime = 'application/csv'
        ratt = Types.ResourceAttributes()
        ratt.fileName = "Advanced Tags Mapping.csv"
        ratt.attachment = True
        tagmapcsv.attributes = ratt
        #tagmapcsv.attributes.append(ratt)

        #2 add resource to main content
        note = Types.Note()
        note.title = 'Advanced Tags Mapping'
        note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
        note.content += "<en-note>"
        note.content += "<br /><en-media hash=\"%s\" type=\"%s\" /><br />" % (
            hexhash, tagmapcsv.mime)
        note.content += "</en-note>"

        #3 add resource to resource list
        if note.resources == None: note.resources = []
        note.resources.append(tagmapcsv)

        #4 upload note
        note = self.noteStore.createNote(self.token, note)

        #print("")
        return note
Esempio n. 24
0
 def open_note(self, guid, insert_in_content=True, **unk_args):
     import hashlib, mimetypes
     view = self.window.active_view()
     filename = view.file_name() or ""
     if view is None:
         self.message("You need to open the file to be attached first!")
         return
     contents = view.substr(sublime.Region(0, view.size())).encode('utf8')
     try:
         noteStore = self.get_note_store()
         note = noteStore.getNote(self.token(), guid, True, False, False,
                                  False)
         mime = mimetypes.guess_type(filename)
         h = hashlib.md5(contents)
         if not isinstance(mime, str):
             mime = "text/plain"
         attachment = Types.Resource(
             # noteGuid=guid,
             mime=mime,
             data=Types.Data(body=contents,
                             size=len(contents),
                             bodyHash=h.digest()),
             attributes=Types.ResourceAttributes(
                 fileName=os.path.basename(filename), attachment=True))
         resources = note.resources or []
         resources.append(attachment)
         if insert_in_content and note.content.endswith(
                 "</en-note>"):  # just a precaution
             builtin = note.content.find(SUBLIME_EVERNOTE_COMMENT_BEG, 0,
                                         150)
             if builtin >= 0:
                 builtin_end = note.content.find(
                     SUBLIME_EVERNOTE_COMMENT_END, builtin)
                 content = note.content[0:builtin] + note.content[
                     builtin_end + len(SUBLIME_EVERNOTE_COMMENT_END) + 1:]
             else:
                 content = note.content
             note.content = content[0:-10] + \
                 '<en-media hash="%s" type="%s"/></en-note>' % (h.hexdigest(), mime)
         note.resources = resources
         noteStore.updateNote(self.token(), note)
         self.message("Succesfully attached to note '%s'" % note.title)
     except Errors.EDAMNotFoundException as e:
         sublime.error_message(
             "The note with the specified guid could not be found.")
     except Errors.EDAMUserException:
         sublime.error_message(
             "The specified note could not be found.\nPlease check the guid is correct."
         )
Esempio n. 25
0
def create_image_resource(image):
    md5 = hashlib.md5()
    md5.update(image)
    image_hash = md5.digest()

    data = Types.Data()
    data.size = len(image)
    data.bodyHash = image_hash
    data.body = image

    resource = Types.Resource()
    resource.mime = 'image/png'
    resource.data = data

    return (resource, image_hash)
Esempio n. 26
0
 def _create_evernote_resource(attachment_filename,
                               byte_data,
                               source_url=None):
     data = Types.Data(
         bodyHash=hashlib.md5(byte_data).hexdigest(),
         size=len(byte_data),
         body=byte_data,
     )
     return Types.Resource(
         data=data,
         mime=mimetypes.guess_type(attachment_filename)[0],
         attributes=Types.ResourceAttributes(
             sourceURL=source_url,
             fileName=attachment_filename,
         ),
     )
Esempio n. 27
0
    def export(self, note):
        if ['CREATE', self.auth_token_hash, note.hash()] in self.log:
            msg('Skipping since note has already been created (Delete {} to force creation).'
                .format(LOGFILE))
            return
        import evernote.edam.type.ttypes as Types

        # To create a new note, simply create a new Note object and fill in
        # attributes such as the note's title.
        enote = Types.Note()
        enote.created = int(time.mktime(note.ctime.timetuple()))
        enote.title = note.title or 'Untitled'

        # The content of an Evernote note is represented using Evernote Markup Language
        # (ENML). The full ENML specification can be found in the Evernote API Overview
        # at http://dev.evernote.com/documentation/cloud/chapters/ENML.php
        from xml.sax.saxutils import escape
        enote.content = '<?xml version="1.0" encoding="utf-8"?>' + \
                        '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' + \
                        '<en-note>' + \
                        escape(note.text).replace('\n', '<br/>').encode('utf-8')
        enote.resources = []
        for attachment in note.attachments:
            data = Types.Data()
            data.size = len(attachment.data)
            data.bodyHash = hashlib.md5(attachment.data).digest()
            data.body = attachment.data

            resource = Types.Resource()
            mime = attachment.mime or 'image/png'
            resource.mime = mime
            resource.data = data
            enote.resources.append(resource)
            enote.content += '<en-media type="' + mime + '" hash="' + binascii.hexlify(
                data.bodyHash) + '"/>'
        enote.content += '</en-note>'
        enote.tagNames = note.labels

        # Finally, send the new note to Evernote using the createNote method
        # The new Note object that is returned will contain server-generated
        # attributes such as the new note's unique GUID.
        self.note_store.createNote(enote)
        with open(LOGFILE, 'a') as f:
            f.write('# created note at {}\n'.format(
                datetime.now().isoformat(' ')))
            f.write('CREATE {} {}\n'.format(self.auth_token_hash, note.hash()))
Esempio n. 28
0
    def _make_resource(self, filename, mime_type):
        with open(filename, 'rb') as f:
            data_bytes = f.read()
            md5 = hashlib.md5()
            md5.update(data_bytes)

            data = Types.Data()
            data.size = len(data_bytes)
            data.bodyHash = md5.digest()
            data.body = data_bytes

            resource = Types.Resource()
            resource.mime = mime_type
            resource.data = data
            short_name = basename(filename)
            resource.attributes = Types.ResourceAttributes(fileName=short_name)
        return resource, md5.hexdigest()
Esempio n. 29
0
def create_resource(file_path, mime='image/png'):
    """Create a Resource instance for attaching to evernote Note instance

    Parameters
    ----------
    file_path : str
        Indicate file path of the file

    mime : str, optional
        Valid MIME type indicating type of the file

    Returns
    -------
    evernote.edam.type.ttypes.Resource
        The Resource must contain three parts:
            - MIME type
            - content: evernote.edam.type.ttypes.Data
            - hash

    Notes
    -----
    Create string of MD5 sum:
        https://stackoverflow.com/questions/5297448/how-to-get-md5-sum-of-a-string-using-python

    """

    file_data = None
    with open(file_path, 'rb') as f:
        byte_str = f.read()
        file_data = bytearray(byte_str)

    md5 = hashlib.md5()
    md5.update(file_data)
    hexhash = md5.hexdigest()
    data = ttypes.Data()

    # build Resource's necessary data
    data.size = len(file_data)
    data.bodyHash = hexhash
    data.body = file_data

    # build Resource Type
    resource = ttypes.Resource()
    resource.mime = mime
    resource.data = data
    return resource, hexhash
Esempio n. 30
0
    def resourse_append(self, note_in, resource_str, resource_name):
        #0 preparation
        note = Types.Note
        note.guid = ""
        if type(note_in) == type(note):
            note = note_in
            print("append and update")
        if type(note_in) == type(note.guid):
            note.guid = note_in
            note = self.noteStore.getNote(self.token, note.guid, True, True,
                                          True, True)
            print("load, append and update")

        #1 prepare resource
        ## create in memory
        resource = Types.Resource()
        resource.data = Types.Data()
        ## import data.body
        resource.data.body = resource_str
        ## calculate data.hash: and hexhash
        m2 = hashlib.md5()
        m2.update(resource.data.body)
        resource.data.bodyHash = m2.digest()
        hexhash = binascii.hexlify(resource.data.bodyHash)
        ## set the file
        resource.mime = 'application/octet-stream'
        ratt = Types.ResourceAttributes()
        ratt.fileName = resource_name
        ratt.attachment = True
        resource.attributes = ratt
        #resource.attributes.append(ratt)

        #2 add resource tag to the end of main content
        resource_tag_start = note.content.rfind("</en-note>")
        newcontent = note.content[0:resource_tag_start]
        newcontent += "<br /><en-media hash=\"%s\" type=\"%s\" /><br />" % (
            hexhash, resource.mime)
        newcontent += note.content[resource_tag_start:]
        note.content = newcontent
        #3 add resource to list
        if note.resources == None: note.resources = []
        note.resources.append(resource)

        #4 update note
        self.noteStore.updateNote(self.token, note)
        print("appended one resource at the end of note page")