diff --git a/helpers.lua b/helpers.lua index 4e5ce1fa..c8342056 100644 --- a/helpers.lua +++ b/helpers.lua @@ -15,6 +15,8 @@ local io = { lines = io.lines, local rawget = rawget local table = { sort = table.sort } +local Gio = require("lgi").Gio + -- Lain helper functions for internal use -- lain.helpers local helpers = {} @@ -134,6 +136,61 @@ end -- }}} + +-- {{{ Network functions + +-- Create a recieving buffer +-- NOTE: Not sure whether to export this with helpers or not +-- Probably just gonna leave it local for now +function generate_buffer(buffer_length) + -- First, create an output buffer to recieve from + local recv_buffer = " " + -- We'll need to allocate `buffer_length` bytes to it + for i=1,buffer_length do + recv_buffer = recv_buffer .. " " + end + + return recv_buffer +end + +-- Wrapper function to send to any sort of address +function helpers.send_to_address(host, port, data, buffer_length, callback) + -- Have a default buffer length of 1000 + if not buffer_length then + buffer_length = 1000 + end + + -- Generate a buffer to store our result in + local recv_buffer = generate_buffer(buffer_length) + + -- Check if we should be sending to a socket or an IP + local is_socket = (string.sub(host, 1, 1) == "/") + + -- Create a client to listen and send with + local client = Gio.SocketClient() + + local addr + + if is_socket then + addr = Gio.UnixSocketAddress.new(host) + else + local inet_addr = gio.InetAddress.new_from_string(host) + addr = Gio.InetSocketAddress.new(inet_addr, port) + end + + local conn = client:connect(addr) + + local input_stream = conn:get_output_stream() + local output_stream = conn:get_input_stream() + + input_stream:write(data) + output_stream:read(recv_buffer) + output_stream:read(recv_buffer) + + callback(recv_buffer) +end +-- }}} + -- {{{ Misc -- check if an element exist on a table diff --git a/widget/mpd.lua b/widget/mpd.lua index d0b37d7d..f7d885f7 100644 --- a/widget/mpd.lua +++ b/widget/mpd.lua @@ -16,7 +16,8 @@ local wibox = require("wibox") local os = { getenv = os.getenv } local string = { format = string.format, gmatch = string.gmatch, - match = string.match } + match = string.match, + sub = string.sub } -- MPD infos -- lain.widget.mpd @@ -36,16 +37,15 @@ local function factory(args) local followtag = args.followtag or false local settings = args.settings or function() end - local mpdh = string.format("telnet://%s:%s", host, port) - local echo = string.format("printf \"%sstatus\\ncurrentsong\\nclose\\n\"", password) - local cmd = string.format("%s | curl --connect-timeout 1 -fsm 3 %s", echo, mpdh) - + local mpdh = "" + local cmd = "" + local echo = string.format("%sstatus\ncurrentsong\nclose\n", password) + mpd_notification_preset = { title = "Now playing", timeout = 6 } helpers.set_map("current mpd track", nil) - function mpd.update() - helpers.async({ shell, "-c", cmd }, function(f) + helpers.send_to_address(host, port, echo, 10000, function(f) mpd_now = { random_mode = false, single_mode = false,