|
| 1 | +--------------------------------------------------- |
| 2 | +-- Licensed under the GNU General Public License v2 |
| 3 | +-- * (c) 2017, 0x5b <[email protected]> |
| 4 | +--------------------------------------------------- |
| 5 | + |
| 6 | +-- {{{ Grab environment |
| 7 | +local setmetatable = setmetatable |
| 8 | +local pcall = pcall |
| 9 | +local helpers = require("vicious.helpers") |
| 10 | +local spawn = require("awful.spawn") |
| 11 | + |
| 12 | +local success, json = pcall(require, "cjson") |
| 13 | +if not success then |
| 14 | + json = require("json") |
| 15 | +end |
| 16 | + |
| 17 | +local string = { |
| 18 | + sub = string.sub, |
| 19 | + upper = string.upper, |
| 20 | +} |
| 21 | +-- }}} |
| 22 | + |
| 23 | + |
| 24 | +-- Btc: provides current bitcoin price |
| 25 | +-- vicious.widgets.btc |
| 26 | +local btc_all = {} |
| 27 | + |
| 28 | + |
| 29 | +-- {{ Bitcoin widget type |
| 30 | +function btc_all.async(format, warg, callback) |
| 31 | + -- Default values |
| 32 | + if not warg then warg = "usd" end |
| 33 | + |
| 34 | + local btc = { ["{price}"] = "N/A" } |
| 35 | + local currency_code = string.upper(warg) |
| 36 | + local url = "https://api.coindesk.com/v1/bpi/currentprice/" .. currency_code .. ".json" |
| 37 | + local cmd = "curl "..helpers.shellquote(url) |
| 38 | + |
| 39 | + -- {{ Checking response |
| 40 | + local function parse(response) |
| 41 | + -- If 'response' is not json, 'json.decode' will return Error |
| 42 | + local status, data = pcall(function() return json.decode(response) end) |
| 43 | + if not status or not data then |
| 44 | + return btc |
| 45 | + end |
| 46 | + |
| 47 | + btc["{price}"] = string.sub(data["bpi"][currency_code]["rate"], 0, -3) |
| 48 | + return btc |
| 49 | + end |
| 50 | + -- }} |
| 51 | + |
| 52 | + spawn.easy_async(cmd, function(stdout) callback(parse(stdout)) end) |
| 53 | +end |
| 54 | +-- }}} |
| 55 | + |
| 56 | +return btc_all |
0 commit comments