| 1 | #!/usr/bin/env ruby |
|---|
| 2 | # vim:fileencoding=UTF-8: |
|---|
| 3 | =begin |
|---|
| 4 | # hig.rb |
|---|
| 5 | |
|---|
| 6 | ## Launch |
|---|
| 7 | |
|---|
| 8 | $ ruby hig.rb |
|---|
| 9 | |
|---|
| 10 | If you want to help: |
|---|
| 11 | |
|---|
| 12 | $ ruby hig.rb --help |
|---|
| 13 | |
|---|
| 14 | ## Configuration |
|---|
| 15 | |
|---|
| 16 | Options specified by after irc realname. |
|---|
| 17 | |
|---|
| 18 | Configuration example for Tiarra ( http://coderepos.org/share/wiki/Tiarra ). |
|---|
| 19 | |
|---|
| 20 | haiku { |
|---|
| 21 | host: localhost |
|---|
| 22 | port: 16679 |
|---|
| 23 | name: username@example.com athack jabber=username@example.com:jabberpasswd tid=10 ratio=10:3:5 |
|---|
| 24 | password: password on Haiku |
|---|
| 25 | in-encoding: utf8 |
|---|
| 26 | out-encoding: utf8 |
|---|
| 27 | } |
|---|
| 28 | |
|---|
| 29 | ### athack |
|---|
| 30 | |
|---|
| 31 | If `athack` client option specified, |
|---|
| 32 | all nick in join message is leading with @. |
|---|
| 33 | |
|---|
| 34 | So if you complemente nicks (e.g. Irssi), |
|---|
| 35 | it's good for Twitter like reply command (@nick). |
|---|
| 36 | |
|---|
| 37 | In this case, you will see torrent of join messages after connected, |
|---|
| 38 | because NAMES list can't send @ leading nick (it interpreted op.) |
|---|
| 39 | |
|---|
| 40 | ### tid=<color> |
|---|
| 41 | |
|---|
| 42 | Apply id to each message for make favorites by CTCP ACTION. |
|---|
| 43 | |
|---|
| 44 | /me fav id |
|---|
| 45 | |
|---|
| 46 | <color> can be |
|---|
| 47 | |
|---|
| 48 | 0 => white |
|---|
| 49 | 1 => black |
|---|
| 50 | 2 => blue navy |
|---|
| 51 | 3 => green |
|---|
| 52 | 4 => red |
|---|
| 53 | 5 => brown maroon |
|---|
| 54 | 6 => purple |
|---|
| 55 | 7 => orange olive |
|---|
| 56 | 8 => yellow |
|---|
| 57 | 9 => lightgreen lime |
|---|
| 58 | 10 => teal |
|---|
| 59 | 11 => lightcyan cyan aqua |
|---|
| 60 | 12 => lightblue royal |
|---|
| 61 | 13 => pink lightpurple fuchsia |
|---|
| 62 | 14 => grey |
|---|
| 63 | 15 => lightgrey silver |
|---|
| 64 | |
|---|
| 65 | |
|---|
| 66 | ### jabber=<jid>:<pass> |
|---|
| 67 | |
|---|
| 68 | If `jabber=<jid>:<pass>` option specified, |
|---|
| 69 | use jabber to get friends timeline. |
|---|
| 70 | |
|---|
| 71 | You must setup im notifing settings in the site and |
|---|
| 72 | install "xmpp4r-simple" gem. |
|---|
| 73 | |
|---|
| 74 | $ sudo gem install xmpp4r-simple |
|---|
| 75 | |
|---|
| 76 | Be careful for managing password. |
|---|
| 77 | |
|---|
| 78 | ### alwaysim |
|---|
| 79 | |
|---|
| 80 | Use IM instead of any APIs (e.g. post) |
|---|
| 81 | |
|---|
| 82 | ### ratio=<timeline>:<friends>:<channel> |
|---|
| 83 | |
|---|
| 84 | ## License |
|---|
| 85 | |
|---|
| 86 | Ruby's by cho45 |
|---|
| 87 | |
|---|
| 88 | =end |
|---|
| 89 | |
|---|
| 90 | $LOAD_PATH << "lib" |
|---|
| 91 | $LOAD_PATH << "../lib" |
|---|
| 92 | |
|---|
| 93 | $KCODE = "u" if RUBY_VERSION < "1.9" # json use this |
|---|
| 94 | |
|---|
| 95 | require "rubygems" |
|---|
| 96 | require "net/irc" |
|---|
| 97 | require "net/http" |
|---|
| 98 | require "uri" |
|---|
| 99 | require "json" |
|---|
| 100 | require "socket" |
|---|
| 101 | require "time" |
|---|
| 102 | require "logger" |
|---|
| 103 | require "yaml" |
|---|
| 104 | require "pathname" |
|---|
| 105 | require "cgi" |
|---|
| 106 | require "digest/md5" |
|---|
| 107 | |
|---|
| 108 | Net::HTTP.version_1_2 |
|---|
| 109 | |
|---|
| 110 | class HaikuIrcGateway < Net::IRC::Server::Session |
|---|
| 111 | def server_name |
|---|
| 112 | "haikugw" |
|---|
| 113 | end |
|---|
| 114 | |
|---|
| 115 | def server_version |
|---|
| 116 | "0.0.0" |
|---|
| 117 | end |
|---|
| 118 | |
|---|
| 119 | def main_channel |
|---|
| 120 | "#haiku" |
|---|
| 121 | end |
|---|
| 122 | |
|---|
| 123 | def api_base |
|---|
| 124 | URI(ENV["HAIKU_BASE"] || "http://h.hatena.ne.jp/api/") |
|---|
| 125 | end |
|---|
| 126 | |
|---|
| 127 | def api_source |
|---|
| 128 | "hig.rb" |
|---|
| 129 | end |
|---|
| 130 | |
|---|
| 131 | def jabber_bot_id |
|---|
| 132 | nil |
|---|
| 133 | end |
|---|
| 134 | |
|---|
| 135 | def hourly_limit |
|---|
| 136 | 60 |
|---|
| 137 | end |
|---|
| 138 | |
|---|
| 139 | class ApiFailed < StandardError; end |
|---|
| 140 | |
|---|
| 141 | def initialize(*args) |
|---|
| 142 | super |
|---|
| 143 | @channels = {} |
|---|
| 144 | @user_agent = "#{self.class}/#{server_version} (hig.rb)" |
|---|
| 145 | @counters = {} # for jabber fav |
|---|
| 146 | end |
|---|
| 147 | |
|---|
| 148 | def on_user(m) |
|---|
| 149 | super |
|---|
| 150 | post @prefix, JOIN, main_channel |
|---|
| 151 | post server_name, MODE, main_channel, "+o", @prefix.nick |
|---|
| 152 | |
|---|
| 153 | @real, *@opts = @opts.name || @real.split(/\s+/) |
|---|
| 154 | @opts = @opts.inject({}) {|r,i| |
|---|
| 155 | key, value = i.split("=") |
|---|
| 156 | r.update(key => value) |
|---|
| 157 | } |
|---|
| 158 | @tmap = TypableMap.new |
|---|
| 159 | |
|---|
| 160 | if @opts["jabber"] |
|---|
| 161 | jid, pass = @opts["jabber"].split(":", 2) |
|---|
| 162 | @opts["jabber"].replace("jabber=#{jid}:********") |
|---|
| 163 | if jabber_bot_id |
|---|
| 164 | begin |
|---|
| 165 | require "xmpp4r-simple" |
|---|
| 166 | start_jabber(jid, pass) |
|---|
| 167 | rescue LoadError |
|---|
| 168 | log "Failed to start Jabber." |
|---|
| 169 | log 'Installl "xmpp4r-simple" gem or check your id/pass.' |
|---|
| 170 | finish |
|---|
| 171 | end |
|---|
| 172 | else |
|---|
| 173 | @opts.delete("jabber") |
|---|
| 174 | log "This gateway does not support Jabber bot." |
|---|
| 175 | end |
|---|
| 176 | end |
|---|
| 177 | |
|---|
| 178 | log "Client Options: #{@opts.inspect}" |
|---|
| 179 | @log.info "Client Options: #{@opts.inspect}" |
|---|
| 180 | |
|---|
| 181 | timeline_ratio, friends_ratio, channel_ratio = (@opts["ratio"] || "10:3:5").split(":").map {|ratio| ratio.to_i } |
|---|
| 182 | footing = (timeline_ratio + friends_ratio + channel_ratio).to_f |
|---|
| 183 | |
|---|
| 184 | @timeline = [] |
|---|
| 185 | @check_follows_thread = Thread.start do |
|---|
| 186 | loop do |
|---|
| 187 | begin |
|---|
| 188 | check_friends |
|---|
| 189 | check_keywords |
|---|
| 190 | rescue ApiFailed => e |
|---|
| 191 | @log.error e.inspect |
|---|
| 192 | rescue Exception => e |
|---|
| 193 | @log.error e.inspect |
|---|
| 194 | e.backtrace.each do |l| |
|---|
| 195 | @log.error "\t#{l}" |
|---|
| 196 | end |
|---|
| 197 | end |
|---|
| 198 | sleep freq(friends_ratio / footing) |
|---|
| 199 | end |
|---|
| 200 | end |
|---|
| 201 | |
|---|
| 202 | return if @opts["jabber"] |
|---|
| 203 | |
|---|
| 204 | @check_timeline_thread = Thread.start do |
|---|
| 205 | sleep 10 |
|---|
| 206 | loop do |
|---|
| 207 | begin |
|---|
| 208 | check_timeline |
|---|
| 209 | rescue ApiFailed => e |
|---|
| 210 | @log.error e.inspect |
|---|
| 211 | rescue Exception => e |
|---|
| 212 | @log.error e.inspect |
|---|
| 213 | e.backtrace.each do |l| |
|---|
| 214 | @log.error "\t#{l}" |
|---|
| 215 | end |
|---|
| 216 | end |
|---|
| 217 | sleep freq(timeline_ratio / footing) |
|---|
| 218 | end |
|---|
| 219 | end |
|---|
| 220 | end |
|---|
| 221 | |
|---|
| 222 | def on_disconnected |
|---|
| 223 | @check_follows_thread.kill rescue nil |
|---|
| 224 | @check_timeline_thread.kill rescue nil |
|---|
| 225 | @im_thread.kill rescue nil |
|---|
| 226 | @im.disconnect rescue nil |
|---|
| 227 | end |
|---|
| 228 | |
|---|
| 229 | def on_privmsg(m) |
|---|
| 230 | return m[1].ctcps.each {|ctcp| on_ctcp(m[0], ctcp) } if m.ctcp? |
|---|
| 231 | retry_count = 3 |
|---|
| 232 | ret = nil |
|---|
| 233 | target, message = *m.params |
|---|
| 234 | begin |
|---|
| 235 | channel = target.sub(/^#/, "") |
|---|
| 236 | reply = message[/\s+>(.+)$/, 1] |
|---|
| 237 | if !reply && @opts.key?("alwaysim") && @im && @im.connected? # in jabber mode, using jabber post |
|---|
| 238 | message = "##{channel} #{message}" unless "##{channel}" == main_channel |
|---|
| 239 | ret = @im.deliver(jabber_bot_id, message) |
|---|
| 240 | post "#{nick}!#{nick}@#{api_base.host}", TOPIC, channel, message |
|---|
| 241 | else |
|---|
| 242 | channel = "" if "##{channel}" == main_channel |
|---|
| 243 | rid = rid_for(reply) if reply |
|---|
| 244 | if @typo |
|---|
| 245 | log "typo mode. requesting..." |
|---|
| 246 | message.gsub!(/\\n/, "\n") |
|---|
| 247 | file = Net::HTTP.get(URI("http://lab.lowreal.net/test/haiku.rb/?text=" + URI.escape(message))) |
|---|
| 248 | ret = api("statuses/update", {"file" => file, "in_reply_to_status_id" => rid, "keyword" => channel}) |
|---|
| 249 | else |
|---|
| 250 | ret = api("statuses/update", {"status" => message, "in_reply_to_status_id" => rid, "keyword" => channel}) |
|---|
| 251 | end |
|---|
| 252 | log "Status Updated via API" |
|---|
| 253 | end |
|---|
| 254 | raise ApiFailed, "API failed" unless ret |
|---|
| 255 | check_timeline |
|---|
| 256 | rescue => e |
|---|
| 257 | @log.error [retry_count, e.message, e.inspect, e.backtrace].inspect |
|---|
| 258 | if retry_count > 0 |
|---|
| 259 | retry_count -= 1 |
|---|
| 260 | @log.debug "Retry to setting status..." |
|---|
| 261 | # retry |
|---|
| 262 | else |
|---|
| 263 | log "Some Error Happened on Sending #{message}. #{e}" |
|---|
| 264 | end |
|---|
| 265 | end |
|---|
| 266 | end |
|---|
| 267 | |
|---|
| 268 | def on_ctcp(target, message) |
|---|
| 269 | _, command, *args = message.split(/\s+/) |
|---|
| 270 | case command |
|---|
| 271 | when "list" |
|---|
| 272 | nick = args[0] |
|---|
| 273 | @log.debug([ nick, message ]) |
|---|
| 274 | res = api("statuses/user_timeline", { "id" => nick }).reverse_each do |s| |
|---|
| 275 | @log.debug(s) |
|---|
| 276 | post nick, NOTICE, main_channel, s |
|---|
| 277 | end |
|---|
| 278 | |
|---|
| 279 | unless res |
|---|
| 280 | post nil, ERR_NOSUCHNICK, nick, "No such nick/channel" |
|---|
| 281 | end |
|---|
| 282 | when "fav" |
|---|
| 283 | target = args[0] |
|---|
| 284 | st = @tmap[target] |
|---|
| 285 | id = rid_for(target) |
|---|
| 286 | if st || id |
|---|
| 287 | unless id |
|---|
| 288 | if @im && @im.connected? |
|---|
| 289 | # IM のときはいろいろめんどうなことする |
|---|
| 290 | nick, count = *st |
|---|
| 291 | pos = @counters[nick] - count |
|---|
| 292 | @log.debug "%p %s %d/%d => %d" % [ |
|---|
| 293 | st, |
|---|
| 294 | nick, |
|---|
| 295 | count, |
|---|
| 296 | @counters[nick], |
|---|
| 297 | pos |
|---|
| 298 | ] |
|---|
| 299 | res = api("statuses/user_timeline", { "id" => nick }) |
|---|
| 300 | raise ApiFailed, "#{nick} may be private mode" if res.empty? |
|---|
| 301 | if res[pos] |
|---|
| 302 | id = res[pos]["id"] |
|---|
| 303 | else |
|---|
| 304 | raise ApiFailed, "#{pos} of #{nick} is not found." |
|---|
| 305 | end |
|---|
| 306 | else |
|---|
| 307 | id = st["id"] |
|---|
| 308 | end |
|---|
| 309 | end |
|---|
| 310 | res = api("favorites/create/#{id}", {}) |
|---|
| 311 | post nil, NOTICE, main_channel, "Fav: #{res["screen_name"]}: #{res["text"].gsub(URI.regexp(%w|http https|), "http...")}" |
|---|
| 312 | else |
|---|
| 313 | post nil, NOTICE, main_channel, "No such id or status #{target}" |
|---|
| 314 | end |
|---|
| 315 | when "link" |
|---|
| 316 | tid = args[0] |
|---|
| 317 | st = @tmap[tid] |
|---|
| 318 | if st |
|---|
| 319 | st["link"] = (api_base + "/#{st["user"]["screen_name"]}/statuses/#{st["id"]}").to_s unless st["link"] |
|---|
| 320 | post nil, NOTICE, main_channel, st["link"] |
|---|
| 321 | else |
|---|
| 322 | post nil, NOTICE, main_channel, "No such id #{tid}" |
|---|
| 323 | end |
|---|
| 324 | when "typo" |
|---|
| 325 | @typo = !@typo |
|---|
| 326 | post nil, NOTICE, main_channel, "typo mode: #{@typo}" |
|---|
| 327 | end |
|---|
| 328 | rescue ApiFailed => e |
|---|
| 329 | log e.inspect |
|---|
| 330 | end; private :on_ctcp |
|---|
| 331 | |
|---|
| 332 | def on_whois(m) |
|---|
| 333 | nick = m.params[0] |
|---|
| 334 | f = (@friends || []).find {|i| i["screen_name"] == nick } |
|---|
| 335 | if f |
|---|
| 336 | post nil, RPL_WHOISUSER, @nick, nick, nick, api_base.host, "*", "#{f["name"]} / #{f["description"]}" |
|---|
| 337 | post nil, RPL_WHOISSERVER, @nick, nick, api_base.host, api_base.to_s |
|---|
| 338 | post nil, RPL_WHOISIDLE, @nick, nick, "0", "seconds idle" |
|---|
| 339 | post nil, RPL_ENDOFWHOIS, @nick, nick, "End of WHOIS list" |
|---|
| 340 | else |
|---|
| 341 | post nil, ERR_NOSUCHNICK, nick, "No such nick/channel" |
|---|
| 342 | end |
|---|
| 343 | end |
|---|
| 344 | |
|---|
| 345 | def on_join(m) |
|---|
| 346 | channels = m.params[0].split(/\s*,\s*/) |
|---|
| 347 | channels.each do |channel| |
|---|
| 348 | next if channel == main_channel |
|---|
| 349 | begin |
|---|
| 350 | api("keywords/create/#{URI.escape(channel.sub(/^#/, ""))}") |
|---|
| 351 | @channels[channel] = { |
|---|
| 352 | :read => [] |
|---|
| 353 | } |
|---|
| 354 | post "#{@nick}!#{@nick}@#{api_base.host}", JOIN, channel |
|---|
| 355 | rescue => e |
|---|
| 356 | @log.debug e.inspect |
|---|
| 357 | post nil, ERR_NOSUCHNICK, nick, "No such nick/channel" |
|---|
| 358 | end |
|---|
| 359 | end |
|---|
| 360 | end |
|---|
| 361 | |
|---|
| 362 | def on_part(m) |
|---|
| 363 | channel = m.params[0] |
|---|
| 364 | return if channel == main_channel |
|---|
| 365 | @channels.delete(channel) |
|---|
| 366 | api("keywords/destroy/#{URI.escape(channel.sub(/^#/, ""))}") |
|---|
| 367 | post "#{@nick}!#{@nick}@#{api_base.host}", PART, channel |
|---|
| 368 | end |
|---|
| 369 | |
|---|
| 370 | def on_who(m) |
|---|
| 371 | channel = m.params[0] |
|---|
| 372 | case |
|---|
| 373 | when channel == main_channel |
|---|
| 374 | # "<channel> <user> <host> <server> <nick> |
|---|
| 375 | # ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] |
|---|
| 376 | # :<hopcount> <real name>" |
|---|
| 377 | @friends.each do |f| |
|---|
| 378 | user = nick = f["screen_name"] |
|---|
| 379 | host = serv = api_base.host |
|---|
| 380 | real = f["name"] |
|---|
| 381 | post nil, RPL_WHOREPLY, @nick, channel, user, host, serv, nick, "H*@", "0 #{real}" |
|---|
| 382 | end |
|---|
| 383 | post nil, RPL_ENDOFWHO, @nick, channel |
|---|
| 384 | when @groups.key?(channel) |
|---|
| 385 | @groups[channel].each do |name| |
|---|
| 386 | f = @friends.find {|i| i["screen_name"] == name } |
|---|
| 387 | user = nick = f["screen_name"] |
|---|
| 388 | host = serv = api_base.host |
|---|
| 389 | real = f["name"] |
|---|
| 390 | post nil, RPL_WHOREPLY, @nick, channel, user, host, serv, nick, "H*@", "0 #{real}" |
|---|
| 391 | end |
|---|
| 392 | post nil, RPL_ENDOFWHO, @nick, channel |
|---|
| 393 | else |
|---|
| 394 | post nil, ERR_NOSUCHNICK, @nick, nick, "No such nick/channel" |
|---|
| 395 | end |
|---|
| 396 | end |
|---|
| 397 | |
|---|
| 398 | private |
|---|
| 399 | def check_timeline |
|---|
| 400 | api("statuses/friends_timeline").reverse_each do |s| |
|---|
| 401 | begin |
|---|
| 402 | id = s["id"] |
|---|
| 403 | next if id.nil? || @timeline.include?(id) |
|---|
| 404 | @timeline << id |
|---|
| 405 | nick = s["user"]["id"] |
|---|
| 406 | mesg = generate_status_message(s) |
|---|
| 407 | |
|---|
| 408 | tid = @tmap.push(s) |
|---|
| 409 | |
|---|
| 410 | @log.debug [id, nick, mesg] |
|---|
| 411 | |
|---|
| 412 | channel = "##{s["keyword"]}" |
|---|
| 413 | case |
|---|
| 414 | when s["keyword"].match(/^id:/) |
|---|
| 415 | channel = main_channel |
|---|
| 416 | when !@channels.keys.include?(channel) |
|---|
| 417 | channel = main_channel |
|---|
| 418 | mesg = "%s = %s" % [s["keyword"], mesg] |
|---|
| 419 | end |
|---|
| 420 | |
|---|
| 421 | if nick == @nick # 自分のときは topic に |
|---|
| 422 | post "#{nick}!#{nick}@#{api_base.host}", TOPIC, channel, mesg |
|---|
| 423 | else |
|---|
| 424 | if @opts["tid"] |
|---|
| 425 | message(nick, channel, "%s \x03%s [%s]" % [mesg, @opts["tid"], tid]) |
|---|
| 426 | else |
|---|
| 427 | message(nick, channel, "%s" % [mesg, tid]) |
|---|
| 428 | end |
|---|
| 429 | end |
|---|
| 430 | rescue => e |
|---|
| 431 | @log.debug "Error: %p" % e |
|---|
| 432 | end |
|---|
| 433 | end |
|---|
| 434 | @log.debug "@timeline.size = #{@timeline.size}" |
|---|
| 435 | @timeline = @timeline.last(100) |
|---|
| 436 | end |
|---|
| 437 | |
|---|
| 438 | def generate_status_message(s) |
|---|
| 439 | mesg = s["text"] |
|---|
| 440 | mesg.sub!("#{s["keyword"]}=", "") unless s["keyword"] =~ /^id:/ |
|---|
| 441 | mesg << " > #{s["in_reply_to_user_id"]}" unless s["in_reply_to_user_id"].empty? |
|---|
| 442 | |
|---|
| 443 | @log.debug(mesg) |
|---|
| 444 | mesg |
|---|
| 445 | end |
|---|
| 446 | |
|---|
| 447 | def check_friends |
|---|
| 448 | first = true unless @friends |
|---|
| 449 | @friends ||= [] |
|---|
| 450 | friends = api("statuses/friends") |
|---|
| 451 | if first && !@opts.key?("athack") |
|---|
| 452 | @friends = friends |
|---|
| 453 | post nil, RPL_NAMREPLY, @nick, "=", main_channel, @friends.map{|i| "@#{i["screen_name"]}" }.join(" ") |
|---|
| 454 | post nil, RPL_ENDOFNAMES, @nick, main_channel, "End of NAMES list" |
|---|
| 455 | else |
|---|
| 456 | prv_friends = @friends.map {|i| i["screen_name"] } |
|---|
| 457 | now_friends = friends.map {|i| i["screen_name"] } |
|---|
| 458 | |
|---|
| 459 | # Twitter API bug? |
|---|
| 460 | return if !first && (now_friends.length - prv_friends.length).abs > 10 |
|---|
| 461 | |
|---|
| 462 | (now_friends - prv_friends).each do |join| |
|---|
| 463 | join = "@#{join}" if @opts.key?("athack") |
|---|
| 464 | post "#{join}!#{join}@#{api_base.host}", JOIN, main_channel |
|---|
| 465 | end |
|---|
| 466 | (prv_friends - now_friends).each do |part| |
|---|
| 467 | part = "@#{part}" if @opts.key?("athack") |
|---|
| 468 | post "#{part}!#{part}@#{api_base.host}", PART, main_channel, "" |
|---|
| 469 | end |
|---|
| 470 | @friends = friends |
|---|
| 471 | end |
|---|
| 472 | end |
|---|
| 473 | |
|---|
| 474 | def check_keywords |
|---|
| 475 | keywords = api("statuses/keywords").map {|i| "##{i["title"]}" } |
|---|
| 476 | current = @channels.keys |
|---|
| 477 | current.delete main_channel |
|---|
| 478 | |
|---|
| 479 | (current - keywords).each do |part| |
|---|
| 480 | @channels.delete(part) |
|---|
| 481 | post "#{@nick}!#{@nick}@#{api_base.host}", PART, part |
|---|
| 482 | end |
|---|
| 483 | |
|---|
| 484 | (keywords - current).each do |join| |
|---|
| 485 | @channels[join] = { |
|---|
| 486 | :read => [] |
|---|
| 487 | } |
|---|
| 488 | post "#{@nick}!#{@nick}@#{api_base.host}", JOIN, join |
|---|
| 489 | end |
|---|
| 490 | end |
|---|
| 491 | |
|---|
| 492 | def freq(ratio) |
|---|
| 493 | ret = 3600 / (hourly_limit * ratio).round |
|---|
| 494 | @log.debug "Frequency: #{ret}" |
|---|
| 495 | ret |
|---|
| 496 | end |
|---|
| 497 | |
|---|
| 498 | def start_jabber(jid, pass) |
|---|
| 499 | @log.info "Logging-in with #{jid} -> jabber_bot_id: #{jabber_bot_id}" |
|---|
| 500 | @im = Jabber::Simple.new(jid, pass) |
|---|
| 501 | @im.add(jabber_bot_id) |
|---|
| 502 | @im_thread = Thread.start do |
|---|
| 503 | loop do |
|---|
| 504 | begin |
|---|
| 505 | @im.received_messages.each do |msg| |
|---|
| 506 | @log.debug [msg.from, msg.body] |
|---|
| 507 | if msg.from.strip == jabber_bot_id |
|---|
| 508 | # Haiku -> 'nick(id): msg' |
|---|
| 509 | body = msg.body.sub(/^(.+?)(?:\((.+?)\))?: /, "") |
|---|
| 510 | if Regexp.last_match |
|---|
| 511 | nick, id = Regexp.last_match.captures |
|---|
| 512 | body = CGI.unescapeHTML(body) |
|---|
| 513 | |
|---|
| 514 | case |
|---|
| 515 | when nick == "投稿完了" |
|---|
| 516 | log "#{nick}: #{body}" |
|---|
| 517 | when nick == "チャンネル投稿完了" |
|---|
| 518 | log "#{nick}: #{body}" |
|---|
| 519 | when body =~ /^#([a-z_]+)\s+(.+)$/i |
|---|
| 520 | # channel message or not |
|---|
| 521 | message(id || nick, "##{Regexp.last_match[1]}", Regexp.last_match[2]) |
|---|
| 522 | when nick == "photo" && body =~ %r|^http://haiku\.jp/user/([^/]+)/| |
|---|
| 523 | nick = Regexp.last_match[1] |
|---|
| 524 | message(nick, main_channel, body) |
|---|
| 525 | else |
|---|
| 526 | @counters[nick] ||= 0 |
|---|
| 527 | @counters[nick] += 1 |
|---|
| 528 | tid = @tmap.push([nick, @counters[nick]]) |
|---|
| 529 | message(nick, main_channel, "%s \x03%s [%s]" % [body, @opts["tid"], tid]) |
|---|
| 530 | end |
|---|
| 531 | end |
|---|
| 532 | end |
|---|
| 533 | end |
|---|
| 534 | rescue Exception => e |
|---|
| 535 | @log.error "Error on Jabber loop: #{e.inspect}" |
|---|
| 536 | e.backtrace.each do |l| |
|---|
| 537 | @log.error "\t#{l}" |
|---|
| 538 | end |
|---|
| 539 | end |
|---|
| 540 | sleep 1 |
|---|
| 541 | end |
|---|
| 542 | end |
|---|
| 543 | end |
|---|
| 544 | |
|---|
| 545 | def require_post?(path) |
|---|
| 546 | [ |
|---|
| 547 | %r|/update|, |
|---|
| 548 | %r|/create|, |
|---|
| 549 | %r|/destroy|, |
|---|
| 550 | ].any? {|i| i === path } |
|---|
| 551 | end |
|---|
| 552 | |
|---|
| 553 | def api(path, q={}) |
|---|
| 554 | ret = {} |
|---|
| 555 | q["source"] ||= api_source |
|---|
| 556 | |
|---|
| 557 | uri = api_base.dup |
|---|
| 558 | uri.path = "/api/#{path}.json" |
|---|
| 559 | uri.query = q.inject([]) {|r,(k,v)| v ? r << "#{k}=#{URI.escape(v, /[^:,-.!~*'()\w]/n)}" : r }.join("&") |
|---|
| 560 | |
|---|
| 561 | |
|---|
| 562 | req = nil |
|---|
| 563 | if require_post?(path) |
|---|
| 564 | req = Net::HTTP::Post.new(uri.path) |
|---|
| 565 | if q["file"] |
|---|
| 566 | boundary = (rand(0x1_00_00_00_00_00) + 0x1_00_00_00_00_00).to_s(16) |
|---|
| 567 | @log.info boundary |
|---|
| 568 | req["content-type"] = "multipart/form-data; boundary=#{boundary}" |
|---|
| 569 | |
|---|
| 570 | body = "" |
|---|
| 571 | q.each do |k, v| |
|---|
| 572 | body << "--#{boundary}\r\n" |
|---|
| 573 | if k == "file" |
|---|
| 574 | body << "Content-Disposition: form-data; name=\"#{k}\"; filename=\"temp.png\";\r\n" |
|---|
| 575 | body << "Content-Transfer-Encoding: binary\r\n" |
|---|
| 576 | body << "Content-Type: image/png\r\n" |
|---|
| 577 | else |
|---|
| 578 | body << "Content-Disposition: form-data; name=\"#{k}\";\r\n" |
|---|
| 579 | end |
|---|
| 580 | body << "\r\n" |
|---|
| 581 | body << v.to_s |
|---|
| 582 | body << "\r\n" |
|---|
| 583 | end |
|---|
| 584 | body << "--#{boundary}--\r\n" |
|---|
| 585 | |
|---|
| 586 | req.body = body |
|---|
| 587 | uri.query = "" |
|---|
| 588 | else |
|---|
| 589 | req.body = uri.query |
|---|
| 590 | end |
|---|
| 591 | else |
|---|
| 592 | req = Net::HTTP::Get.new(uri.request_uri) |
|---|
| 593 | end |
|---|
| 594 | req.basic_auth(@real, @pass) |
|---|
| 595 | req["User-Agent"] = @user_agent |
|---|
| 596 | req["If-Modified-Since"] = q["since"] if q.key?("since") |
|---|
| 597 | |
|---|
| 598 | @log.debug uri.inspect |
|---|
| 599 | ret = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) } |
|---|
| 600 | |
|---|
| 601 | case ret |
|---|
| 602 | when Net::HTTPOK # 200 |
|---|
| 603 | ret = JSON.parse(ret.body.gsub(/:'/, ':"').gsub(/',/, '",').gsub(/'(y(?:es)?|no?|true|false|null)'/, '"\1"')) |
|---|
| 604 | raise ApiFailed, "Server Returned Error: #{ret["error"]}" if ret.kind_of?(Hash) && ret["error"] |
|---|
| 605 | ret |
|---|
| 606 | when Net::HTTPNotModified # 304 |
|---|
| 607 | [] |
|---|
| 608 | when Net::HTTPBadRequest # 400 |
|---|
| 609 | # exceeded the rate limitation |
|---|
| 610 | raise ApiFailed, "#{ret.code}: #{ret.message}" |
|---|
| 611 | else |
|---|
| 612 | raise ApiFailed, "Server Returned #{ret.code} #{ret.message}" |
|---|
| 613 | end |
|---|
| 614 | rescue Errno::ETIMEDOUT, JSON::ParserError, IOError, Timeout::Error, Errno::ECONNRESET => e |
|---|
| 615 | raise ApiFailed, e.inspect |
|---|
| 616 | end |
|---|
| 617 | |
|---|
| 618 | def message(sender, target, str) |
|---|
| 619 | sender = "#{sender}!#{sender}@#{api_base.host}" |
|---|
| 620 | post sender, PRIVMSG, target, str.gsub(/\s+/, " ") |
|---|
| 621 | end |
|---|
| 622 | |
|---|
| 623 | def log(str) |
|---|
| 624 | str.gsub!(/\n/, " ") |
|---|
| 625 | post server_name, NOTICE, main_channel, str |
|---|
| 626 | end |
|---|
| 627 | |
|---|
| 628 | # return rid of most recent matched status with text |
|---|
| 629 | def rid_for(text) |
|---|
| 630 | target = Regexp.new(Regexp.quote(text.strip), "i") |
|---|
| 631 | status = api("statuses/friends_timeline").find {|i| |
|---|
| 632 | next false if i["user"]["name"] == @nick # 自分は除外 |
|---|
| 633 | i["text"] =~ target |
|---|
| 634 | } |
|---|
| 635 | |
|---|
| 636 | @log.debug "Looking up status contains #{text.inspect} -> #{status.inspect}" |
|---|
| 637 | status ? status["id"] : nil |
|---|
| 638 | end |
|---|
| 639 | |
|---|
| 640 | class TypableMap < Hash |
|---|
| 641 | Roman = %w[ |
|---|
| 642 | k g ky gy s z sh j t d ch n ny h b p hy by py m my y r ry w v q |
|---|
| 643 | ].unshift("").map do |consonant| |
|---|
| 644 | case consonant |
|---|
| 645 | when "y", /\A.{2}/ then %w|a u o| |
|---|
| 646 | when "q" then %w|a i e o| |
|---|
| 647 | else %w|a i u e o| |
|---|
| 648 | end.map {|vowel| "#{consonant}#{vowel}" } |
|---|
| 649 | end.flatten |
|---|
| 650 | |
|---|
| 651 | def initialize(size = 1) |
|---|
| 652 | @seq = Roman |
|---|
| 653 | @n = 0 |
|---|
| 654 | @size = size |
|---|
| 655 | end |
|---|
| 656 | |
|---|
| 657 | def generate(n) |
|---|
| 658 | ret = [] |
|---|
| 659 | begin |
|---|
| 660 | n, r = n.divmod(@seq.size) |
|---|
| 661 | ret << @seq[r] |
|---|
| 662 | end while n > 0 |
|---|
| 663 | ret.reverse.join |
|---|
| 664 | end |
|---|
| 665 | |
|---|
| 666 | def push(obj) |
|---|
| 667 | id = generate(@n) |
|---|
| 668 | self[id] = obj |
|---|
| 669 | @n += 1 |
|---|
| 670 | @n %= @seq.size ** @size |
|---|
| 671 | id |
|---|
| 672 | end |
|---|
| 673 | alias << push |
|---|
| 674 | |
|---|
| 675 | def clear |
|---|
| 676 | @n = 0 |
|---|
| 677 | super |
|---|
| 678 | end |
|---|
| 679 | |
|---|
| 680 | private :[]= |
|---|
| 681 | undef update, merge, merge!, replace |
|---|
| 682 | end |
|---|
| 683 | |
|---|
| 684 | |
|---|
| 685 | end |
|---|
| 686 | |
|---|
| 687 | if __FILE__ == $0 |
|---|
| 688 | require "optparse" |
|---|
| 689 | |
|---|
| 690 | opts = { |
|---|
| 691 | :port => 16679, |
|---|
| 692 | :host => "localhost", |
|---|
| 693 | :log => nil, |
|---|
| 694 | :debug => false, |
|---|
| 695 | :foreground => false, |
|---|
| 696 | } |
|---|
| 697 | |
|---|
| 698 | OptionParser.new do |parser| |
|---|
| 699 | parser.instance_eval do |
|---|
| 700 | self.banner = <<-EOB.gsub(/^\t+/, "") |
|---|
| 701 | Usage: #{$0} [opts] |
|---|
| 702 | |
|---|
| 703 | EOB |
|---|
| 704 | |
|---|
| 705 | separator "" |
|---|
| 706 | |
|---|
| 707 | separator "Options:" |
|---|
| 708 | on("-p", "--port [PORT=#{opts[:port]}]", "port number to listen") do |port| |
|---|
| 709 | opts[:port] = port |
|---|
| 710 | end |
|---|
| 711 | |
|---|
| 712 | on("-h", "--host [HOST=#{opts[:host]}]", "host name or IP address to listen") do |host| |
|---|
| 713 | opts[:host] = host |
|---|
| 714 | end |
|---|
| 715 | |
|---|
| 716 | on("-l", "--log LOG", "log file") do |log| |
|---|
| 717 | opts[:log] = log |
|---|
| 718 | end |
|---|
| 719 | |
|---|
| 720 | on("--debug", "Enable debug mode") do |debug| |
|---|
| 721 | opts[:log] = $stdout |
|---|
| 722 | opts[:debug] = true |
|---|
| 723 | end |
|---|
| 724 | |
|---|
| 725 | on("-f", "--foreground", "run foreground") do |foreground| |
|---|
| 726 | opts[:log] = $stdout |
|---|
| 727 | opts[:foreground] = true |
|---|
| 728 | end |
|---|
| 729 | |
|---|
| 730 | on("-n", "--name [user name or email address]") do |name| |
|---|
| 731 | opts[:name] = name |
|---|
| 732 | end |
|---|
| 733 | |
|---|
| 734 | parse!(ARGV) |
|---|
| 735 | end |
|---|
| 736 | end |
|---|
| 737 | |
|---|
| 738 | opts[:logger] = Logger.new(opts[:log], "daily") |
|---|
| 739 | opts[:logger].level = opts[:debug] ? Logger::DEBUG : Logger::INFO |
|---|
| 740 | |
|---|
| 741 | # def daemonize(foreground=false) |
|---|
| 742 | # trap("SIGINT") { exit! 0 } |
|---|
| 743 | # trap("SIGTERM") { exit! 0 } |
|---|
| 744 | # trap("SIGHUP") { exit! 0 } |
|---|
| 745 | # return yield if $DEBUG || foreground |
|---|
| 746 | # Process.fork do |
|---|
| 747 | # Process.setsid |
|---|
| 748 | # Dir.chdir "/" |
|---|
| 749 | # File.open("/dev/null") {|f| |
|---|
| 750 | # STDIN.reopen f |
|---|
| 751 | # STDOUT.reopen f |
|---|
| 752 | # STDERR.reopen f |
|---|
| 753 | # } |
|---|
| 754 | # yield |
|---|
| 755 | # end |
|---|
| 756 | # exit! 0 |
|---|
| 757 | # end |
|---|
| 758 | |
|---|
| 759 | # daemonize(opts[:debug] || opts[:foreground]) do |
|---|
| 760 | Net::IRC::Server.new(opts[:host], opts[:port], HaikuIrcGateway, opts).start |
|---|
| 761 | # end |
|---|
| 762 | end |
|---|
| 763 | |
|---|
| 764 | # Local Variables: |
|---|
| 765 | # coding: utf-8 |
|---|
| 766 | # End: |
|---|