Created
November 9, 2016 13:18
-
-
Save ravage/62a0946e99bb43a97e92507a975a051f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "./guronsan/*" | |
require "json" | |
require "http" | |
module Guronsan | |
module Command | |
extend self | |
def run(command, args = nil) | |
io = String::Builder.new | |
Process.run(command, args: args, shell: true, output: io) | |
io.to_s | |
end | |
def lastlogin | |
result = run("last | head -1 | awk '{print $1,$3,$4,$5,$6}'").split() | |
username = result[0] | |
datetime = result[1..-1].join(' ') | |
dt = Time.parse(datetime, "%a %b %-d %R") | |
dt = Time.new(Time.now.year, dt.month, dt.day, dt.hour, dt.minute) | |
{ username, dt } | |
end | |
def send(body) | |
client = HTTP::Client.new("127.0.0.1", 8081) | |
headers = HTTP::Headers.new | |
headers.add("User-Agent", "Guronsan") | |
headers.add("Content-Type", "application/json") | |
client.post("/", headers, body.to_json) do |response| | |
puts response.status_code | |
end | |
end | |
end | |
module Message | |
struct Payload(T) | |
def initialize(@command : String, @payload : T) | |
end | |
JSON.mapping({ | |
command: String, | |
payload: { type: T } | |
}) | |
end | |
struct LastLogin | |
def initialize(@username : String, @datetime : Time) | |
end | |
JSON.mapping({ | |
username: String, | |
datetime: { type: Time, converter: Time::EpochConverter } | |
}) | |
end | |
end | |
username, datetime = Command.lastlogin | |
lastlogin = Message::LastLogin.new(username, datetime) | |
payload = Message::Payload.new("lastlogin", lastlogin) | |
# output | |
puts payload.to_json | |
# consume | |
puts Message::Payload(Message::LastLogin).from_json(payload.to_json) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment