Skip to content

Instantly share code, notes, and snippets.

@hotchpotch
Created August 28, 2008 12:46
Show Gist options
  • Save hotchpotch/7715 to your computer and use it in GitHub Desktop.
Save hotchpotch/7715 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'pit'
require 'fusefs'
require 'atomutil'
require 'time'
module Atompub
class HatenaClient < Client
def publish_entry(uri)
@hatena_publish = true
update_resource(uri, ' ', Atom::MediaType::ENTRY.to_s)
ensure
@hatena_publish = false
end
private
def set_common_info(req)
req['X-Hatena-Publish'] = 1 if @hatena_publish
super(req)
end
end
end
module HatenaDiaryFS
class Base
TIME_FORMAT = '%Y%m%d%H%M%S'
def initialize(config)
@config = config
auth = Atompub::Auth::Wsse.new config
@client = Atompub::HatenaClient.new :auth => auth
@service = @client.get_service 'http://d.hatena.ne.jp/%s/atom' % config[:username]
end
def feed
@client.get_feed collection_uri
end
def entries
@entries ||= feed.entries
end
def find_entry_by_time(time)
time = time.strftime TIME_FORMAT if time.kind_of? Time
entries.find {|e|
e.updated.strftime(TIME_FORMAT) == time
}
end
end
class Blog < Base
CREATE_PATH = '/create'
def collection_uri
collection_uri = @service.workspace.collections[1].href
end
def contents(path)
['create'] + (entries.map {|e| e.updated.strftime TIME_FORMAT } || [])
end
def file?(path)
path == CREATE_PATH || !! find_entry_by_time(path.sub(/^\//, ''))
end
def read_file(path)
begin
e = find_entry_by_time(path.sub(/^\//, ''))
if e
resource, _ = @client.get_media e.edit_link
el = Atom::Entry.new(:stream => resource)
body = el.get('http://www.hatena.ne.jp/info/xmlns#', 'syntax').text
[e.title, body].join("\n")
else
''
end
rescue Exception => e
puts ['read error', e, e.backtrace].flatten.join("\n")
end
end
def can_delete?(path)
true
end
def delete(path)
begin
entry = find_entry_by_time(path.sub(/^\//, ''))
@client.delete_entry entry.edit_link
@entries = nil
rescue Exception => e
puts ['delete error', e, e.backtrace].flatten.join("\n")
end
end
def can_write?(path)
!!(path == CREATE_PATH || path.match(/^\/\d{14}/))
end
def write_to(path, body)
begin
entry = find_entry_by_time(path.sub(/^\//, ''))
title, body = body.split("\n", 2)
if entry
entry.title = title
entry.content = Atom::Content.new(:body => body, :type => 'text')
@client.update_entry entry.edit_link, entry
else
entry = Atom::Entry.new(
:title => title,
:content => body,
:updated => (path == 'create' ? Time.now : Time.parse(path) )
)
@client.create_entry collection_uri, entry
end
@entries = nil
rescue Exception => e
puts ['write error', e, e.backtrace].flatten.join("\n")
end
end
end
end
config = Pit.get('hatena', :require => {
:username => "hatena_id",
:password => "hatena_password"
})
h_blog_fs = HatenaDiaryFS::Blog.new(config)
FuseFS.set_root(h_blog_fs)
FuseFS.mount_under ARGV.first
FuseFS.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment