Skip to content

Instantly share code, notes, and snippets.

@oogali
Created August 30, 2012 13:37
Show Gist options
  • Save oogali/3528688 to your computer and use it in GitHub Desktop.
Save oogali/3528688 to your computer and use it in GitHub Desktop.
Read your Notes from iCloud
#!/usr/bin/env ruby
#
# quick class to read your most recent notes from icloud
# @oogali
#
require 'rubygems'
require 'net/imap'
require 'time'
require 'nokogiri'
require 'mail'
class Notes
@list
@imap
@username
def initialize(username, passwd, host = 'mail.me.com', port = 993, ssl = true)
@imap = Net::IMAP.new host, port, ssl
@imap.login username, passwd
# save username
@username = username
@username += '@me.com' unless username.include? '@me.com'
@imap.select 'Notes'
list true
end
def list(refresh = false)
return @list unless refresh
@list = @imap.sort(['DATE'], ['ALL'], 'US-ASCII').reverse
end
def close
@imap.expunge
@imap.logout
@imap.disconnect
end
def get(num = nil, &block)
note = @imap.fetch(num || @list.first, ['UID', 'INTERNALDATE', 'RFC822.TEXT', 'RFC822.HEADER']).first
notes = {
:ts => Time.parse(note.attr['INTERNALDATE']),
:uid => note.attr['UID'],
:raw => note.attr['RFC822.TEXT'],
:headers => note.attr['RFC822.HEADER'],
:uuid => note.attr['RFC822.HEADER'].scan(/X-Universally-Unique-Identifier: (\S+)/)[0][0],
:items => Nokogiri::HTML(note.attr['RFC822.TEXT'].gsub("=\r\n", '')).xpath('//div').map { |x| x.text }
}
# get the title, then delete the blank line after the title
notes[:title] = notes[:items].shift
notes[:items].delete_at(0)
if block_given?
case block.arity
when 5
yield notes[:ts], notes[:uid], notes[:uuid], notes[:title], notes[:items]
else
yield notes
end
else
notes
end
end
def save(uuid, title, items)
builder = Nokogiri::HTML::Builder.new do |doc|
doc.html {
doc.head {}
doc.body(:style => 'word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;') {
doc.div { doc.b title }
doc.div { doc.br }
items.each do |item|
doc.div item
end
}
}
end
msg = Mail.new
msg['From'] = @username
msg['Subject'] = title
msg['X-Uniform-Type-Identifier'] = 'com.apple.mail-note'
msg['Content-Type'] = 'text/html; charset=us-ascii'
msg['Content-Transfer-Encoding'] = 'quoted-printable'
msg['Mime-Version'] = "1.0 (Mac OS X Notes 1.0 \\(81\\))"
msg['X-Universally-Unique-Identifier'] = uuid
@imap.append 'Notes', msg.to_s + builder.to_html.to_s.gsub("\n", "\r\n")
#@imap.store @list.first, '+FLAGS', [:Deleted]
#@imap.expunge
msg.to_s
end
end
notes = Notes.new USERNAME, PASSWORD
notes.get do |ts, uid, uuid, title, items|
i = 1
items.each do |item|
puts "#{i}. #{item}"
i += 1
end
#p notes.save uuid, title, items
end
notes.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment