| 1 | #!/usr/bin/env ruby |
|---|
| 2 | # vim:encoding=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" # 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 | @map = nil |
|---|
| 146 | @counters = {} # for jabber fav |
|---|
| 147 | end |
|---|
| 148 | |
|---|
| 149 | def on_user(m) |
|---|
| 150 | super |
|---|
| 151 | post @prefix, JOIN, main_channel |
|---|
| 152 | post server_name, MODE, main_channel, "+o", @prefix.nick |
|---|
| 153 | |
|---|
| 154 | @real, *@opts = @opts.name || @real.split(/\s+/) |
|---|
| 155 | @opts = @opts.inject({}) {|r,i| |
|---|
| 156 | key, value = i.split("=") |
|---|
| 157 | r.update(key => value) |
|---|
| 158 | } |
|---|
| 159 | @tmap = TypableMap.new |
|---|
| 160 | |
|---|
| 161 | if @opts["jabber"] |
|---|
| 162 | jid, pass = @opts["jabber"].split(":", 2) |
|---|
| 163 | @opts["jabber"].replace("jabber=#{jid}:********") |
|---|
| 164 | if jabber_bot_id |
|---|
| 165 | begin |
|---|
| 166 | require "xmpp4r-simple" |
|---|
| 167 | start_jabber(jid, pass) |
|---|
| 168 | rescue LoadError |
|---|
| 169 | log "Failed to start Jabber." |
|---|
| 170 | log 'Installl "xmpp4r-simple" gem or check your id/pass.' |
|---|
| 171 | finish |
|---|
| 172 | end |
|---|
| 173 | else |
|---|
| 174 | @opts.delete("jabber") |
|---|
| 175 | log "This gateway does not support Jabber bot." |
|---|
| 176 | end |
|---|
| 177 | end |
|---|
| 178 | |
|---|
| 179 | log "Client Options: #{@opts.inspect}" |
|---|
| 180 | @log.info "Client Options: #{@opts.inspect}" |
|---|
| 181 | |
|---|
| 182 | timeline_ratio, friends_ratio, channel_ratio = (@opts["ratio"] || "10:3:5").split(":").map {|ratio| ratio.to_i } |
|---|
| 183 | footing = (timeline_ratio + friends_ratio + channel_ratio).to_f |
|---|
| 184 | |
|---|
| 185 | @timeline = [] |
|---|
| 186 | @check_follows_thread = Thread.start do |
|---|
| 187 | loop do |
|---|
| 188 | begin |
|---|
| 189 | check_friends |
|---|
| 190 | check_keywords |
|---|
| 191 | rescue ApiFailed => e |
|---|
| 192 | @log.error e.inspect |
|---|
| 193 | rescue Exception => e |
|---|
| 194 | @log.error e.inspect |
|---|
| 195 | e.backtrace.each do |l| |
|---|
| 196 | @log.error "\t#{l}" |
|---|
| 197 | end |
|---|
| 198 | end |
|---|
| 199 | sleep freq(friends_ratio / footing) |
|---|
| 200 | end |
|---|
| 201 | end |
|---|
| 202 | |
|---|
| 203 | return if @opts["jabber"] |
|---|
| 204 | |
|---|
| 205 | @check_timeline_thread = Thread.start do |
|---|
| 206 | sleep 10 |
|---|
| 207 | loop do |
|---|
| 208 | begin |
|---|
| 209 | check_timeline |
|---|
| 210 | rescue ApiFailed => e |
|---|
| 211 | @log.error e.inspect |
|---|
| 212 | rescue Exception => e |
|---|
| 213 | @log.error e.inspect |
|---|
| 214 | e.backtrace.each do |l| |
|---|
| 215 | @log.error "\t#{l}" |
|---|
| 216 | end |
|---|
| 217 | end |
|---|
| 218 | sleep freq(timeline_ratio / footing) |
|---|
| 219 | end |
|---|
| 220 | end |
|---|
| 221 | end |
|---|
| 222 | |
|---|
| 223 | def on_disconnected |
|---|
| 224 | @check_follows_thread.kill rescue nil |
|---|
| 225 | @check_timeline_thread.kill rescue nil |
|---|
| 226 | @im_thread.kill rescue nil |
|---|
| 227 | @im.disconnect rescue nil |
|---|
| 228 | end |
|---|
| 229 | |
|---|
| 230 | def on_privmsg(m) |
|---|
| 231 | return on_ctcp(m[0], ctcp_decoding(m[1])) if m.ctcp? |
|---|
| 232 | retry_count = 3 |
|---|
| 233 | ret = nil |
|---|
| 234 | target, message = *m.params |
|---|
| 235 | begin |
|---|
| 236 | channel = target.sub(/^#/, "") |
|---|
| 237 | reply = message[/\s+>(.+)$/, 1] |
|---|
| 238 | if !reply && @opts.key?("alwaysim") && @im && @im.connected? # in jabber mode, using jabber post |
|---|
| 239 | message = "##{channel} #{message}" unless "##{channel}" == main_channel |
|---|
| 240 | ret = @im.deliver(jabber_bot_id, message) |
|---|
| 241 | post "#{nick}!#{nick}@#{api_base.host}", TOPIC, channel, message |
|---|
| 242 | else |
|---|
| 243 | channel = "" if "##{channel}" == main_channel |
|---|
| 244 | rid = rid_for(reply) if reply |
|---|
| 245 | if @typo |
|---|
| 246 | log "typo mode. requesting..." |
|---|
| 247 | message.gsub!(/\\n/, "\n") |
|---|
| 248 | file = Net::HTTP.get(URI("http://lab.lowreal.net/test/haiku.rb/?text=" + URI.escape(message))) |
|---|
| 249 | ret = api("statuses/update", {"file" => file, "in_reply_to_status_id" => rid, "keyword" => channel}) |
|---|
| 250 | else |
|---|
| 251 | ret = api("statuses/update", {"status" => message, "in_reply_to_status_id" => rid, "keyword" => channel}) |
|---|
| 252 | end |
|---|
| 253 | log "Status Updated via API" |
|---|
| 254 | end |
|---|
| 255 | raise ApiFailed, "API failed" unless ret |
|---|
| 256 | check_timeline |
|---|
| 257 | rescue => e |
|---|
| 258 | @log.error [retry_count, e.message, e.inspect, e.backtrace].inspect |
|---|
| 259 | if retry_count > 0 |
|---|
| 260 | retry_count -= 1 |
|---|
| 261 | @log.debug "Retry to setting status..." |
|---|
| 262 | # retry |
|---|
| 263 | else |
|---|
| 264 | log "Some Error Happened on Sending #{message}. #{e}" |
|---|
| 265 | end |
|---|
| 266 | end |
|---|
| 267 | end |
|---|
| 268 | |
|---|
| 269 | def on_ctcp(target, message) |
|---|
| 270 | _, command, *args = message.split(/\s+/) |
|---|
| 271 | case command |
|---|
| 272 | when "list" |
|---|
| 273 | nick = args[0] |
|---|
| 274 | @log.debug([ nick, message ]) |
|---|
| 275 | res = api("statuses/user_timeline", { "id" => nick }).reverse_each do |s| |
|---|
| 276 | @log.debug(s) |
|---|
| 277 | post nick, NOTICE, main_channel, s |
|---|
| 278 | end |
|---|
| 279 | |
|---|
| 280 | unless res |
|---|
| 281 | post nil, ERR_NOSUCHNICK, nick, "No such nick/channel" |
|---|
| 282 | end |
|---|
| 283 | when "fav" |
|---|
| 284 | target = args[0] |
|---|
| 285 | st = @tmap[target] |
|---|
| 286 | id = rid_for(target) |
|---|
| 287 | if st || id |
|---|
| 288 | unless id |
|---|
| 289 | if @im && @im.connected? |
|---|
| 290 | # IM のときはいろいろめんどうなことする |
|---|
| 291 | nick, count = *st |
|---|
| 292 | pos = @counters[nick] - count |
|---|
| 293 | @log.debug "%p %s %d/%d => %d" % [ |
|---|
| 294 | st, |
|---|
| 295 | nick, |
|---|
| 296 | count, |
|---|
| 297 | @counters[nick], |
|---|
| 298 | pos |
|---|
| 299 | ] |
|---|
| 300 | res = api("statuses/user_timeline", { "id" => nick }) |
|---|
| 301 | raise ApiFailed, "#{nick} may be private mode" if res.empty? |
|---|
| 302 | if res[pos] |
|---|
| 303 | id = res[pos]["id"] |
|---|
| 304 | else |
|---|
| 305 | raise ApiFailed, "#{pos} of #{nick} is not found." |
|---|
| 306 | end |
|---|
| 307 | else |
|---|
| 308 | id = st["id"] |
|---|
| 309 | end |
|---|
| 310 | end |
|---|
| 311 | res = api("favorites/create/#{id}", {}) |
|---|
| 312 | post nil, NOTICE, main_channel, "Fav: #{res["screen_name"]}: #{res["text"].gsub(URI.regexp(%w|http https|), "http...")}" |
|---|
| 313 | else |
|---|
| 314 | post nil, NOTICE, main_channel, "No such id or status #{target}" |
|---|
| 315 | end |
|---|
| 316 | when "link" |
|---|
| 317 | tid = args[0] |
|---|
| 318 | st = @tmap[tid] |
|---|
| 319 | if st |
|---|
| 320 | st["link"] = (api_base + "/#{st["user"]["screen_name"]}/statuses/#{st["id"]}").to_s unless st["link"] |
|---|
| 321 | post nil, NOTICE, main_channel, st["link"] |
|---|
| 322 | else |
|---|
| 323 | post nil, NOTICE, main_channel, "No such id #{tid}" |
|---|
| 324 | end |
|---|
| 325 | when "typo" |
|---|
| 326 | @typo = !@typo |
|---|
| 327 | post nil, NOTICE, main_channel, "typo mode: #{@typo}" |
|---|
| 328 | end |
|---|
| 329 | rescue ApiFailed => e |
|---|
| 330 | log e.inspect |
|---|
| 331 | end |
|---|
| 332 | |
|---|
| 333 | def on_whois(m) |
|---|
| 334 | nick = m.params[0] |
|---|
| 335 | f = (@friends || []).find {|i| i["screen_name"] == nick } |
|---|
| 336 | if f |
|---|
| 337 | post nil, RPL_WHOISUSER, @nick, nick, nick, api_base.host, "*", "#{f["name"]} / #{f["description"]}" |
|---|
| 338 | post nil, RPL_WHOISSERVER, @nick, nick, api_base.host, api_base.to_s |
|---|
| 339 | post nil, RPL_WHOISIDLE, @nick, nick, "0", "seconds idle" |
|---|
| 340 | post nil, RPL_ENDOFWHOIS, @nick, nick, "End of WHOIS list" |
|---|
| 341 | else |
|---|
| 342 | post nil, ERR_NOSUCHNICK, nick, "No such nick/channel" |
|---|
| 343 | end |
|---|
| 344 | end |
|---|
| 345 | |
|---|
| 346 | def on_join(m) |
|---|
| 347 | channels = m.params[0].split(/\s*,\s*/) |
|---|
| 348 | channels.each do |channel| |
|---|
| 349 | next if channel == main_channel |
|---|
| 350 | begin |
|---|
| 351 | api("keywords/create/#{URI.escape(channel.sub(/^#/, ""))}") |
|---|
| 352 | @channels[channel] = { |
|---|
| 353 | :read => [] |
|---|
| 354 | } |
|---|
| 355 | post "#{@nick}!#{@nick}@#{api_base.host}", JOIN, channel |
|---|
| 356 | rescue => e |
|---|
| 357 | @log.debug e.inspect |
|---|
| 358 | post nil, ERR_NOSUCHNICK, nick, "No such nick/channel" |
|---|
| 359 | end |
|---|
| 360 | end |
|---|
| 361 | end |
|---|
| 362 | |
|---|
| 363 | def on_part(m) |
|---|
| 364 | channel = m.params[0] |
|---|
| 365 | return if channel == main_channel |
|---|
| 366 | @channels.delete(channel) |
|---|
| 367 | api("keywords/destroy/#{URI.escape(channel.sub(/^#/, ""))}") |
|---|
| 368 | post "#{@nick}!#{@nick}@#{api_base.host}", PART, channel |
|---|
| 369 | end |
|---|
| 370 | |
|---|
| 371 | def on_who(m) |
|---|
| 372 | channel = m.params[0] |
|---|
| 373 | case |
|---|
| 374 | when channel == main_channel |
|---|
| 375 | # "<channel> <user> <host> <server> <nick> |
|---|
| 376 | # ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] |
|---|
| 377 | # :<hopcount> <real name>" |
|---|
| 378 | @friends.each do |f| |
|---|
| 379 | user = nick = f["screen_name"] |
|---|
| 380 | host = serv = api_base.host |
|---|
| 381 | real = f["name"] |
|---|
| 382 | post nil, RPL_WHOREPLY, @nick, channel, user, host, serv, nick, "H*@", "0 #{real}" |
|---|
| 383 | end |
|---|
| 384 | post nil, RPL_ENDOFWHO, @nick, channel |
|---|
| 385 | when @groups.key?(channel) |
|---|
| 386 | @groups[channel].each do |name| |
|---|
| 387 | f = @friends.find {|i| i["screen_name"] == name } |
|---|
| 388 | user = nick = f["screen_name"] |
|---|
| 389 | host = serv = api_base.host |
|---|
| 390 | real = f["name"] |
|---|
| 391 | post nil, RPL_WHOREPLY, @nick, channel, user, host, serv, nick, "H*@", "0 #{real}" |
|---|
| 392 | end |
|---|
| 393 | post nil, RPL_ENDOFWHO, @nick, channel |
|---|
| 394 | else |
|---|
| 395 | post nil, ERR_NOSUCHNICK, @nick, nick, "No such nick/channel" |
|---|
| 396 | end |
|---|
| 397 | end |
|---|
| 398 | |
|---|
| 399 | private |
|---|
| 400 | def check_timeline |
|---|
| 401 | api("statuses/friends_timeline").reverse_each do |s| |
|---|
| 402 | begin |
|---|
| 403 | id = s["id"] |
|---|
| 404 | next if id.nil? || @timeline.include?(id) |
|---|
| 405 | @timeline << id |
|---|
| 406 | nick = s["user"]["id"] |
|---|
| 407 | mesg = generate_status_message(s) |
|---|
| 408 | |
|---|
| 409 | tid = @tmap.push(s) |
|---|
| 410 | |
|---|
| 411 | @log.debug [id, nick, mesg] |
|---|
| 412 | |
|---|
| 413 | channel = "##{s["keyword"]}" |
|---|
| 414 | case |
|---|
| 415 | when s["keyword"].match(/^id:/) |
|---|
| 416 | channel = main_channel |
|---|
| 417 | when !@channels.keys.include?(channel) |
|---|
| 418 | channel = main_channel |
|---|
| 419 | mesg = "%s = %s" % [s["keyword"], mesg] |
|---|
| 420 | end |
|---|
| 421 | |
|---|
| 422 | if nick == @nick # 自分のときは topic に |
|---|
| 423 | post "#{nick}!#{nick}@#{api_base.host}", TOPIC, channel, mesg |
|---|
| 424 | else |
|---|
| 425 | if @opts["tid"] |
|---|
| 426 | message(nick, channel, "%s \x03%s [%s]" % [mesg, @opts["tid"], tid]) |
|---|
| 427 | else |
|---|
| 428 | message(nick, channel, "%s" % [mesg, tid]) |
|---|
| 429 | end |
|---|
| 430 | end |
|---|
| 431 | rescue => e |
|---|
| 432 | @log.debug "Error: %p" % e |
|---|
| 433 | end |
|---|
| 434 | end |
|---|
| 435 | @log.debug "@timeline.size = #{@timeline.size}" |
|---|
| 436 | @timeline = @timeline.last(100) |
|---|
| 437 | end |
|---|
| 438 | |
|---|
| 439 | def generate_status_message(s) |
|---|
| 440 | mesg = s["text"] |
|---|
| 441 | mesg.sub!("#{s["keyword"]}=", "") unless s["keyword"] =~ /^id:/ |
|---|
| 442 | mesg << " > #{s["in_reply_to_user_id"]}" unless s["in_reply_to_user_id"].empty? |
|---|
| 443 | |
|---|
| 444 | @log.debug(mesg) |
|---|
| 445 | mesg |
|---|
| 446 | end |
|---|
| 447 | |
|---|
| 448 | def check_friends |
|---|
| 449 | first = true unless @friends |
|---|
| 450 | @friends ||= [] |
|---|
| 451 | friends = api("statuses/friends") |
|---|
| 452 | if first && !@opts.key?("athack") |
|---|
| 453 | @friends = friends |
|---|
| 454 | post nil, RPL_NAMREPLY, @nick, "=", main_channel, @friends.map{|i| "@#{i["screen_name"]}" }.join(" ") |
|---|
| 455 | post nil, RPL_ENDOFNAMES, @nick, main_channel, "End of NAMES list" |
|---|
| 456 | else |
|---|
| 457 | prv_friends = @friends.map {|i| i["screen_name"] } |
|---|
| 458 | now_friends = friends.map {|i| i["screen_name"] } |
|---|
| 459 | |
|---|
| 460 | # Twitter API bug? |
|---|
| 461 | return if !first && (now_friends.length - prv_friends.length).abs > 10 |
|---|
| 462 | |
|---|
| 463 | (now_friends - prv_friends).each do |join| |
|---|
| 464 | join = "@#{join}" if @opts.key?("athack") |
|---|
| 465 | post "#{join}!#{join}@#{api_base.host}", JOIN, main_channel |
|---|
| 466 | end |
|---|
| 467 | (prv_friends - now_friends).each do |part| |
|---|
| 468 | part = "@#{part}" if @opts.key?("athack") |
|---|
| 469 | post "#{part}!#{part}@#{api_base.host}", PART, main_channel, "" |
|---|
| 470 | end |
|---|
| 471 | @friends = friends |
|---|
| 472 | end |
|---|
| 473 | end |
|---|
| 474 | |
|---|
| 475 | def check_keywords |
|---|
| 476 | keywords = api("statuses/keywords").map {|i| "##{i["title"]}" } |
|---|
| 477 | current = @channels.keys |
|---|
| 478 | current.delete main_channel |
|---|
| 479 | |
|---|
| 480 | (current - keywords).each do |part| |
|---|
| 481 | @channels.delete(part) |
|---|
| 482 | post "#{@nick}!#{@nick}@#{api_base.host}", PART, part |
|---|
| 483 | end |
|---|
| 484 | |
|---|
| 485 | (keywords - current).each do |join| |
|---|
| 486 | @channels[join] = { |
|---|
| 487 | :read => [] |
|---|
| 488 | } |
|---|
| 489 | post "#{@nick}!#{@nick}@#{api_base.host}", JOIN, join |
|---|
| 490 | end |
|---|
| 491 | end |
|---|
| 492 | |
|---|
| 493 | def freq(ratio) |
|---|
| 494 | ret = 3600 / (hourly_limit * ratio).round |
|---|
| 495 | @log.debug "Frequency: #{ret}" |
|---|
| 496 | ret |
|---|
| 497 | end |
|---|
| 498 | |
|---|
| 499 | def start_jabber(jid, pass) |
|---|
| 500 | @log.info "Logging-in with #{jid} -> jabber_bot_id: #{jabber_bot_id}" |
|---|
| 501 | @im = Jabber::Simple.new(jid, pass) |
|---|
| 502 | @im.add(jabber_bot_id) |
|---|
| 503 | @im_thread = Thread.start do |
|---|
| 504 | loop do |
|---|
| 505 | begin |
|---|
| 506 | @im.received_messages.each do |msg| |
|---|
| 507 | @log.debug [msg.from, msg.body] |
|---|
| 508 | if msg.from.strip == jabber_bot_id |
|---|
| 509 | # Haiku -> 'nick(id): msg' |
|---|
| 510 | body = msg.body.sub(/^(.+?)(?:\((.+?)\))?: /, "") |
|---|
| 511 | if Regexp.last_match |
|---|
| 512 | nick, id = Regexp.last_match.captures |
|---|
| 513 | body = CGI.unescapeHTML(body) |
|---|
| 514 | |
|---|
| 515 | case |
|---|
| 516 | when nick == "投稿完了" |
|---|
| 517 | log "#{nick}: #{body}" |
|---|
| 518 | when nick == "チャンネル投稿完了" |
|---|
| 519 | log "#{nick}: #{body}" |
|---|
| 520 | when body =~ /^#([a-z_]+)\s+(.+)$/i |
|---|
| 521 | # channel message or not |
|---|
| 522 | message(id || nick, "##{Regexp.last_match[1]}", Regexp.last_match[2]) |
|---|
| 523 | when nick == "photo" && body =~ %r|^http://haiku\.jp/user/([^/]+)/| |
|---|
| 524 | nick = Regexp.last_match[1] |
|---|
| 525 | message(nick, main_channel, body) |
|---|
| 526 | else |
|---|
| 527 | @counters[nick] ||= 0 |
|---|
| 528 | @counters[nick] += 1 |
|---|
| 529 | tid = @tmap.push([nick, @counters[nick]]) |
|---|
| 530 | message(nick, main_channel, "%s \x03%s [%s]" % [body, @opts["tid"], tid]) |
|---|
| 531 | end |
|---|
| 532 | end |
|---|
| 533 | end |
|---|
| 534 | end |
|---|
| 535 | rescue Exception => e |
|---|
| 536 | @log.error "Error on Jabber loop: #{e.inspect}" |
|---|
| 537 | e.backtrace.each do |l| |
|---|
| 538 | @log.error "\t#{l}" |
|---|
| 539 | end |
|---|
| 540 | end |
|---|
| 541 | sleep 1 |
|---|
| 542 | end |
|---|
| 543 | end |
|---|
| 544 | end |
|---|
| 545 | |
|---|
| 546 | def require_post?(path) |
|---|
| 547 | [ |
|---|
| 548 | %r|/update|, |
|---|
| 549 | %r|/create|, |
|---|
| 550 | %r|/destroy|, |
|---|
| 551 | ].any? {|i| i === path } |
|---|
| 552 | end |
|---|
| 553 | |
|---|
| 554 | def api(path, q={}) |
|---|
| 555 | ret = {} |
|---|
| 556 | q["source"] ||= api_source |
|---|
| 557 | |
|---|
| 558 | uri = api_base.dup |
|---|
| 559 | uri.path = "/api/#{path}.json" |
|---|
| 560 | uri.query = q.inject([]) {|r,(k,v)| v ? r << "#{k}=#{URI.escape(v, /[^:,-.!~*'()\w]/n)}" : r }.join("&") |
|---|
| 561 | |
|---|
| 562 | |
|---|
| 563 | req = nil |
|---|
| 564 | if require_post?(path) |
|---|
| 565 | req = Net::HTTP::Post.new(uri.path) |
|---|
| 566 | if q["file"] |
|---|
| 567 | boundary = (rand(0x1_00_00_00_00_00) + 0x1_00_00_00_00_00).to_s(16) |
|---|
| 568 | @log.info boundary |
|---|
| 569 | req["content-type"] = "multipart/form-data; boundary=#{boundary}" |
|---|
| 570 | |
|---|
| 571 | body = "" |
|---|
| 572 | q.each do |k, v| |
|---|
| 573 | body << "--#{boundary}\r\n" |
|---|
| 574 | if k == "file" |
|---|
| 575 | body << "Content-Disposition: form-data; name=\"#{k}\"; filename=\"temp.png\";\r\n" |
|---|
| 576 | body << "Content-Transfer-Encoding: binary\r\n" |
|---|
| 577 | body << "Content-Type: image/png\r\n" |
|---|
| 578 | else |
|---|
| 579 | body << "Content-Disposition: form-data; name=\"#{k}\";\r\n" |
|---|
| 580 | end |
|---|
| 581 | body << "\r\n" |
|---|
| 582 | body << v.to_s |
|---|
| 583 | body << "\r\n" |
|---|
| 584 | end |
|---|
| 585 | body << "--#{boundary}--\r\n" |
|---|
| 586 | |
|---|
| 587 | req.body = body |
|---|
| 588 | uri.query = "" |
|---|
| 589 | else |
|---|
| 590 | req.body = uri.query |
|---|
| 591 | end |
|---|
| 592 | else |
|---|
| 593 | req = Net::HTTP::Get.new(uri.request_uri) |
|---|
| 594 | end |
|---|
| 595 | req.basic_auth(@real, @pass) |
|---|
| 596 | req["User-Agent"] = @user_agent |
|---|
| 597 | req["If-Modified-Since"] = q["since"] if q.key?("since") |
|---|
| 598 | |
|---|
| 599 | @log.debug uri.inspect |
|---|
| 600 | ret = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) } |
|---|
| 601 | |
|---|
| 602 | case ret |
|---|
| 603 | when Net::HTTPOK # 200 |
|---|
| 604 | ret = JSON.parse(ret.body.gsub(/:'/, ':"').gsub(/',/, '",').gsub(/'(y(?:es)?|no?|true|false|null)'/, '"\1"')) |
|---|
| 605 | raise ApiFailed, "Server Returned Error: #{ret["error"]}" if ret.kind_of?(Hash) && ret["error"] |
|---|
| 606 | ret |
|---|
| 607 | when Net::HTTPNotModified # 304 |
|---|
| 608 | [] |
|---|
| 609 | when Net::HTTPBadRequest # 400 |
|---|
| 610 | # exceeded the rate limitation |
|---|
| 611 | raise ApiFailed, "#{ret.code}: #{ret.message}" |
|---|
| 612 | else |
|---|
| 613 | raise ApiFailed, "Server Returned #{ret.code} #{ret.message}" |
|---|
| 614 | end |
|---|
| 615 | rescue Errno::ETIMEDOUT, JSON::ParserError, IOError, Timeout::Error, Errno::ECONNRESET => e |
|---|
| 616 | raise ApiFailed, e.inspect |
|---|
| 617 | end |
|---|
| 618 | |
|---|
| 619 | def message(sender, target, str) |
|---|
| 620 | sender = "#{sender}!#{sender}@#{api_base.host}" |
|---|
| 621 | post sender, PRIVMSG, target, str.gsub(/\s+/, " ") |
|---|
| 622 | end |
|---|
| 623 | |
|---|
| 624 | def log(str) |
|---|
| 625 | str.gsub!(/\n/, " ") |
|---|
| 626 | post server_name, NOTICE, main_channel, str |
|---|
| 627 | end |
|---|
| 628 | |
|---|
| 629 | # return rid of most recent matched status with text |
|---|
| 630 | def rid_for(text) |
|---|
| 631 | target = Regexp.new(Regexp.quote(text.strip), "i") |
|---|
| 632 | status = api("statuses/friends_timeline").find {|i| |
|---|
| 633 | next false if i["user"]["name"] == @nick # 自分は除外 |
|---|
| 634 | i["text"] =~ target |
|---|
| 635 | } |
|---|
| 636 | |
|---|
| 637 | @log.debug "Looking up status contains #{text.inspect} -> #{status.inspect}" |
|---|
| 638 | status ? status["id"] : nil |
|---|
| 639 | end |
|---|
| 640 | |
|---|
| 641 | class TypableMap < Hash |
|---|
| 642 | Roma = %w|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|.unshift("").map {|consonant| |
|---|
| 643 | case |
|---|
| 644 | when consonant.size > 1, consonant == "y" |
|---|
| 645 | %w|a u o| |
|---|
| 646 | when consonant == "q" |
|---|
| 647 | %w|a i e o| |
|---|
| 648 | else |
|---|
| 649 | %w|a i u e o| |
|---|
| 650 | end.map {|vowel| "#{consonant}#{vowel}" } |
|---|
| 651 | }.flatten |
|---|
| 652 | |
|---|
| 653 | def initialize(size=1) |
|---|
| 654 | @seq = Roma |
|---|
| 655 | @map = {} |
|---|
| 656 | @n = 0 |
|---|
| 657 | @size = size |
|---|
| 658 | end |
|---|
| 659 | |
|---|
| 660 | def generate(n) |
|---|
| 661 | ret = [] |
|---|
| 662 | begin |
|---|
| 663 | n, r = n.divmod(@seq.size) |
|---|
| 664 | ret << @seq[r] |
|---|
| 665 | end while n > 0 |
|---|
| 666 | ret.reverse.join |
|---|
| 667 | end |
|---|
| 668 | |
|---|
| 669 | def push(obj) |
|---|
| 670 | id = generate(@n) |
|---|
| 671 | self[id] = obj |
|---|
| 672 | @n += 1 |
|---|
| 673 | @n = @n % (@seq.size ** @size) |
|---|
| 674 | id |
|---|
| 675 | end |
|---|
| 676 | alias << push |
|---|
| 677 | |
|---|
| 678 | def clear |
|---|
| 679 | @n = 0 |
|---|
| 680 | super |
|---|
| 681 | end |
|---|
| 682 | |
|---|
| 683 | private :[]= |
|---|
| 684 | undef update, merge, merge!, replace |
|---|
| 685 | end |
|---|
| 686 | |
|---|
| 687 | |
|---|
| 688 | end |
|---|
| 689 | |
|---|
| 690 | if __FILE__ == $0 |
|---|
| 691 | require "optparse" |
|---|
| 692 | |
|---|
| 693 | opts = { |
|---|
| 694 | :port => 16679, |
|---|
| 695 | :host => "localhost", |
|---|
| 696 | :log => nil, |
|---|
| 697 | :debug => false, |
|---|
| 698 | :foreground => false, |
|---|
| 699 | } |
|---|
| 700 | |
|---|
| 701 | OptionParser.new do |parser| |
|---|
| 702 | parser.instance_eval do |
|---|
| 703 | self.banner = <<-EOB.gsub(/^\t+/, "") |
|---|
| 704 | Usage: #{$0} [opts] |
|---|
| 705 | |
|---|
| 706 | EOB |
|---|
| 707 | |
|---|
| 708 | separator "" |
|---|
| 709 | |
|---|
| 710 | separator "Options:" |
|---|
| 711 | on("-p", "--port [PORT=#{opts[:port]}]", "port number to listen") do |port| |
|---|
| 712 | opts[:port] = port |
|---|
| 713 | end |
|---|
| 714 | |
|---|
| 715 | on("-h", "--host [HOST=#{opts[:host]}]", "host name or IP address to listen") do |host| |
|---|
| 716 | opts[:host] = host |
|---|
| 717 | end |
|---|
| 718 | |
|---|
| 719 | on("-l", "--log LOG", "log file") do |log| |
|---|
| 720 | opts[:log] = log |
|---|
| 721 | end |
|---|
| 722 | |
|---|
| 723 | on("--debug", "Enable debug mode") do |debug| |
|---|
| 724 | opts[:log] = $stdout |
|---|
| 725 | opts[:debug] = true |
|---|
| 726 | end |
|---|
| 727 | |
|---|
| 728 | on("-f", "--foreground", "run foreground") do |foreground| |
|---|
| 729 | opts[:log] = $stdout |
|---|
| 730 | opts[:foreground] = true |
|---|
| 731 | end |
|---|
| 732 | |
|---|
| 733 | on("-n", "--name [user name or email address]") do |name| |
|---|
| 734 | opts[:name] = name |
|---|
| 735 | end |
|---|
| 736 | |
|---|
| 737 | parse!(ARGV) |
|---|
| 738 | end |
|---|
| 739 | end |
|---|
| 740 | |
|---|
| 741 | opts[:logger] = Logger.new(opts[:log], "daily") |
|---|
| 742 | opts[:logger].level = opts[:debug] ? Logger::DEBUG : Logger::INFO |
|---|
| 743 | |
|---|
| 744 | # def daemonize(foreground=false) |
|---|
| 745 | # trap("SIGINT") { exit! 0 } |
|---|
| 746 | # trap("SIGTERM") { exit! 0 } |
|---|
| 747 | # trap("SIGHUP") { exit! 0 } |
|---|
| 748 | # return yield if $DEBUG || foreground |
|---|
| 749 | # Process.fork do |
|---|
| 750 | # Process.setsid |
|---|
| 751 | # Dir.chdir "/" |
|---|
| 752 | # File.open("/dev/null") {|f| |
|---|
| 753 | # STDIN.reopen f |
|---|
| 754 | # STDOUT.reopen f |
|---|
| 755 | # STDERR.reopen f |
|---|
| 756 | # } |
|---|
| 757 | # yield |
|---|
| 758 | # end |
|---|
| 759 | # exit! 0 |
|---|
| 760 | # end |
|---|
| 761 | |
|---|
| 762 | # daemonize(opts[:debug] || opts[:foreground]) do |
|---|
| 763 | Net::IRC::Server.new(opts[:host], opts[:port], HaikuIrcGateway, opts).start |
|---|
| 764 | # end |
|---|
| 765 | end |
|---|
| 766 | |
|---|
| 767 | # Local Variables: |
|---|
| 768 | # coding: utf-8 |
|---|
| 769 | # End: |
|---|