# encoding: UTF-8 =begin Copyright 2020 Marek Küthe This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. =end module BOB require "socket" class BOBResponse def self.iws sock full = String.new ans = sock.gets while ans[0...4] == "DATA" full += ans ans = sock.gets end full += ans BOBResponse.new full end def initialize ans @ans = ans.chomp @parsed = false self.parse! end def data? ! @data.nil? end def ok? @status == "OK" end def error? @status == "ERROR" end def answer @ans end def content @content end def data @data end def status @status end def parse! if @ans[0...4] == "DATA" @data = Array.new @ans.lines.each { |x| x.chomp! if x[0...4] == "DATA" @data.push x[5..-1] elsif x[0...2] == "OK" @status = x[0...2] @content = x[3..-1] end } elsif @ans[0...2] == "OK" @status = @ans[0...2] @content = @ans[3..-1] elsif @ans[0...5] == "ERROR" @status = @ans[0...5] @content = @ans[6..-1] end @parsed = true end end class BOBRequest def initialize cmd, args = String.new @cmd = cmd @args = args end def full_request "#{@cmd} #{@args}\n" end def send sock sock.puts self.full_request sleep 2 if @cmd == "stop" end end class BOBInitial def self.iws sock BOBInitial.new sock.gets, sock.gets end def initialize line1, line2 @line1 = line1.chomp @line2 = line2.chomp self.parse! end def parse! @apiname = @line1[0...3] @version = @line1[4..-1] @bobstatus = @line2 end def apiname @apiname end def version @version end def status @bobstatus end def ok? @bobstatus == "OK" end def error? @bobstatus == "ERROR" end end class BOBConnection < TCPSocket def initialize host="127.0.0.1", port=2827, autoclosemessage=true super host, port @acm = autoclosemessage @bobinitial = BOBInitial.iws self end def version @bobinitial.version end def ready? @bobinitial.ok? and not self.closed? end def close if @acm self.puts "quit" ans = self.gets.chomp raise RuntimeError, "BOB: #{ans}", caller if ans != "OK Bye!" end super end end def BOB.bobshutdown bob = BOBConnection.new "127.0.0.1", "2827", false BOBRequest.new("zap").send bob ans = BOBResponse.iws bob bob.close return (bob.closed? and ans.ok?) end end