heimdall/client.rb

101 lines
2.4 KiB
Ruby
Executable File

#!/usr/bin/ruby
require 'readline'
require 'net/http'
require 'json'
require 'uri'
puts "Connecting to server #{ARGV[0]} on port #{ARGV[1]}"
def get(path)
where = URI("http://#{ARGV[0]}:#{ARGV[1]}/#{path}")
JSON.parse(Net::HTTP.get(where))
end
def post(path,data)
where = URI("http://#{ARGV[0]}:#{ARGV[1]}/#{path}")
Net::HTTP.post(where,data.to_json)
end
version = get("version")["version"]
puts "Server reported version: #{version}"
print "Nickname> "
nickname = $stdin.gets.strip
puts "Trying to log in..."
res = get("/user/exists?protocol_id=#{"heimdall-"+nickname}")
puts "Account exists! exiting" if res["exists"]
return if res["exists"]
puts "Creating account..."
test = post("/user/new",{username: nickname, protocol_id: "heimdall-"+nickname})
unless test.kind_of? Net::HTTPOK then
puts "Something went wrong! exiting"
exit
end
puts "Your id is: heimdall-#{nickname}"
Thread.new do
while true do
sleep 1
messages = get("/user/read?protocol_id=#{"heimdall-"+nickname}")
if messages["error"] then
puts "Error: #{messages["error"]}"
next
end
messages["messages"].each { |x|
puts "#{x["user"]["username"]} says: #{x["content"]}"
}
end
end
target = nil
at_exit do
post("/user/delete",{
"protocol_id"=> "heimdall-"+nickname
})
end
while buf = Readline.readline("> ", true)
if buf == "/help" then
puts "Commands:"
puts "/help - this message"
puts "/send <protcol_id> - direct messages to somebody"
puts "/exit - quit program"
puts "/find <username> - find a username by pattern"
puts "/find-protoid <protoid> - find by a protocol id"
next
end
if buf == "/exit" then
post("/user/delete",{
"protocol_id"=> "heimdall-"+nickname
})
exit
end
if buf.match(/^\/send .*$/) then
target = buf.match(/^\/send ([^\s]*)$/)[1]
next
end
if buf.match(/^\/find .*$/) then
uname = (buf.match /^\/find (.*)$/)[1]
users = get("/user/find/by-username?username=#{uname}")["results"]
puts "Found #{users.length} results: "
users.each { |x| puts x[0] }
next
end
if buf.match(/^\/find-protoid .*$/) then
pid = (buf.match /^\/find-protoid (.*)$/)[1]
users = get("/user/find/by-protoid?protocol_id=#{pid}")["results"]
puts "Found #{users.length} results: "
users.each { |x| puts x[0] }
next
end
if target then
post("/user/send", {
"to" => target,
"content" => buf,
"from" => "heimdall-"+nickname
})
end
end