LoginSignup
5
6

More than 5 years have passed since last update.

fluent-plugin-hatena-bookmarkつくった

Last updated at Posted at 2013-07-15

いちいちgemにしてリポジトリつくるほどでもない単純なものなのでコピペではっつけておきますが

↑このgemに依存しています。

out_hatena_bookmark.rb
class Fluent::HatenaBookmarkOutput < Fluent::Output
  Fluent::Plugin.register_output('hatena_bookmark', self)

  config_param :consumer_key, :string
  config_param :consumer_secret, :string
  config_param :request_token, :string
  config_param :request_secret, :string

  def initialize
    super
    require 'hatena-bookmark'
  end 

  def configure(conf)
    super
    @hatebu = Hatena::Bookmark.new(
      consumer_key:    conf['consumer_key'],
      consumer_secret: conf['consumer_secret'],
      request_token:   conf['request_token'],
      request_secret:  conf['request_secret']
    )   
  end 

  def emit(tag, es, chain)
    es.each do |time, record|
      create_or_edit(record)
    end 
    chain.next
  end 

  def create_or_edit(record)
    begin
      if record['tag'].class == String
        tag = [record['tag']]
      else
        tag = record['tag']
      end
      comment = tag.map{|t| "[#{t}]"}.join('')
      res = @hatebu.create(:url => record['url'], :comment => comment)
      res_comment = res["entry"]["summary"]
      # レスポンスのsummaryが投稿した内容と同一でないとき、
      # ブックマーク済みのURLをcreateしようとしたため無視されている
      if res_comment != comment
        eid = res["entry"]["id"].split("-").last
        # 重複していないものだけtag文字列として追加する
        res_tags = res_comment.scan(/\[(.*?)\]/).map{|t| p t[0]}
        new_tags = (tag - res_tags).map{|t| "[#{t}]"}.join('')
        new_comment = "#{new_tags}#{res["entry"]["summary"]}"
        $log.info(new_comment)
        rese = @hatebu.put_edit(:eid => eid, :url => record['url'], :comment => new_comment)
      end
    rescue => e
      $log.error(e)
      $log.error('hatebu post failed')
    end
  end

end

これは以下のようなJSON構造がemitされてくることを期待しています。

{"tag":["tech","ruby"],"title":"hatena-bookmark | RubyGems.org | your community gem host","url":"https://rubygems.org/gems/hatena-bookmark"}

または

{"tag":"tech","title":"hatena-bookmark | RubyGems.org | your community gem host","url":"https://rubygems.org/gems/hatena-bookmark"}

titleは使ってないのであってもなくてもよい。

すでにブックマーク済みのページだった場合はタグを上書きで追加するようにした。

fluentdのin_httpのようにHTTP待ち受けする機能をつかえば、はてブのWebHook APIを受信してinputもできるようになりそうだが、いまのところ使うあてがない割には大変そうなので今回はやらない

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6