Skip to content

Instantly share code, notes, and snippets.

@giginet
Created November 24, 2009 21:17
Show Gist options
  • Save giginet/242229 to your computer and use it in GitHub Desktop.
Save giginet/242229 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'mechanize'
require 'rss'
require 'yaml'
require 'open-uri'
######################
#HBtomixi Ver1.0
#はてなダイアリの記事とmixiを同期させます。
#詳細や使い方など:
#コードの改変、再配布は出典明記の上可
#<今後の機能追加予定>
#YouTube、ニコニコ動画埋め込みに対応?
#指定したカテゴリの記事は同期させない設定?
#お問い合わせ:
#twitter:@giginetおよび、上記エントリのコメント欄で
######################
$config =YAML.load_file("HDtomixi.yaml")
#File.open(config['CACHEFILE'],'w')
class Entry
@@loggedin =false
@@userid = $config['mixi_userid']
def initialize(title,description,link)
@title =title
@description = description
@link = link
end
def show #デバッグ用、タイトルをはき出す
puts @title
end
def CheckCache #キャッシュに同じIDが存在しているか検
begin
@flag =true
#キャッシュファイルを読み込む
File.open($config['CACHEFILE'],"r").each do |f|
if f.gsub(/\s/,"") == @link
@flag =false
return false
break
end
end
rescue
#なかった場合はファイルを生成してリトライ
File.open($config['CACHEFILE'],"a")
retry
end
return @flag
end
def WriteCache #キャッシュに書き込む
f= File.open($config['CACHEFILE'],"a")
f.puts @link
f.close
end
def Normalize #記事を整形して正規化
#改行タグを改行コードに
@description = @description.gsub(/\<br\>/,"\n")
#imgタグの画像をアップロードして、埋め込み用のタグ生成
@imgtags = @description.scan(/\<img.*?\>/)
@imgtags.each do |img|
url = img.scan(/src=".*?"/)[0].gsub(/(^src=)*"/,"")
@image = Image.new(url)
@image.UploadTomixi(true)
@replace = Time.now.to_s
@phototag = @image.CreateImageTag << "\n"
@description = @description.sub(img,@replace)
end
#<photo src="40810414:2880880876">
#画像タグを埋め込み
#aタグを発見して変更
@atags = @description.scan(/\<a\s.*\>.*\<\/a\>/)
@atags.each do |link|
href = link.scan(/href=".*?"/)
href = href[0].gsub(/(^href=)*"/,"")
classname = link.scan(/class=".*?"/)
if classname[0] != nil
classname = classname[0].gsub(/^class=/,"").gsub(/"/,"")
end
if classname !="keyword"
text = link.gsub(/\<\/*a\s*.*?\>/,"") << "(" << href << ")"
@description = @description.sub(link,text)
end
end
#タグを全削除
@description = @description.gsub(/\<([^(photo)]|.)*?\>/,"")
#引用元情報
@description << "元記事:"<<@link
#カテゴリ非表示設定の時、タイトルのカテゴリを削除する
if $config['DISABLECATEGORY']
@title = @title.gsub(/^\[.*\]/,"")
end
#Photoタグ復帰
@description = @description.gsub(@replace,@phototag)
puts @description
end
def Upload #記事をmixi日記にアップロードする
#Login
self.Login;
#記事をポスト
@url = 'http://mixi.jp/add_diary.pl?id='<<$config['mixi_userid']
page = @@agent.get(@url)
form = page.forms[1]
form['diary_title']= @title
form['diary_body']= @description
page = form.submit
#確認画面
form = page.forms[1]
form.submit
puts @title
puts "posted!"
end
def Login #mixiにログインする
if @@loggedin==false
puts "Login"
@@agent = WWW::Mechanize.new
#mixiにログイン
page = @@agent.get("http://mixi.jp/")
form = page.forms.first
form.field_with(:name=>'email').value = $config['mixi_username']
form.field_with(:name=>'password').value =$config['mixi_password']
form.submit
@@loggedin = true
end
end
end
class Image < Entry
def initialize(imageurl)
#フォルダの生成
#画像をダウンロードして専用フォルダに
@filename = Time.now.to_s << File.basename(imageurl)
@dir =$config['UPLOADDIR']
File.open("#{@dir}/#{@filename}",'wb') do |file|
open(imageurl) do |data|
file.write(data.read)
end
end
puts "Fetching Image..."
@image = File.open("#{@dir}/#{@filename}",'rb')
end
def UploadTomixi(press)
#画像は、URLのみに変換
#ダウンロードした画像をフォトアルバムに自動でアップロード
self.Login
url = "http://mixi.jp/add_album_photo.pl?id=#{$config['PHOTOALBUM']}&owner_id=#{$config['mixi_userid']}"
page = @@agent.get(url)
form = page.forms[1]
form.file_upload_with(:name => 'photo1').file_name = File.join(File.expand_path($config['UPLOADDIR']),@filename)
page = form.submit
#確認画面
form = page.forms[1]
form.submit
puts "Uploading Image..."
sleep 10
#うp済みの画像をフォルダから削除
File.delete("#{@dir}/#{@filename}")
end
def CreateImageTag
#画像をタグに変換
#一番後ろにある画像ファイル名を取ってくればたぶん大丈夫・・・
url = "http://mixi.jp/view_album.pl?id=#{$config['PHOTOALBUM']}&owner_id=#{$config['mixi_userid']}"
page = @@agent.get(url)
regexp = Regexp.new("#{$config['PHOTOALBUM']}_.*\.jpg","","u")
urls = page.body.scan(regexp)
@image_url = urls.last
@image_url =@image_url.gsub(/\.jpg$/,"").gsub(/_/,":")
@imagetag = '<photo src="' << @image_url << '">'
return @imagetag
end
end
#はてなダイアリからキャッシュにない最新記事を取得
entries = Array.new
rssurl = "http://d.hatena.ne.jp/#{$config['hatena_username'].to_s}/rss"
RSS::Parser.parse(open(rssurl){|h|h.read}, false).items.each do |item|
entry = Entry.new(item.title,item.content_encoded,item.link)
entries.push(entry)
end
entries.reverse!
entries.each do |e|
if e.CheckCache #キャッシュに存在しているかをチェック
#記事を正規化
e.Normalize
#キャッシュに書き込み
e.WriteCache
#記事を更新
e.Upload
sleep 10
end
end
#mixiのログイン用メールアドレス
mixi_username: 'foobar@example.com'
#mixiのログイン用パスワード
mixi_password: 'hogepiyo'
#mixiのユーザーID
mixi_userid: '0000000'
#はてなユーザー名
hatena_username: 'gigi-net'
#キャッシュファイル名
CACHEFILE: "HDtomixi.dat"
#はてダタイトルのカテゴリ/^([.*])*/を消去するか
DISABLECATEGORY: true
#画像をアップロードするか(未実装)
UPLOADIMAGE: true
#mixiフォトアルバムのリサイズ機能を有効にするか(未実装)
PRESSIMAGE: true
#画像ファイルをキャッシュしておくディレクトリ
UPLOADDIR: "HDtomixi_images"
#画像アップ先のmixiフォトアルバムID
PHOTOALBUM: "40810414"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment