Debian Codegraph @

vicious/contrib/btc_all.lua

raw symbols SCIP
1 -- contrib/btc_all.lua
2 -- Copyright (C) 2017 0x5b <[email protected]>
3 -- Copyright (C) 2017 Joerg Thalheim <[email protected]>
4 -- Copyright (C) 2019 Nguyễn Gia Phong <[email protected]m>
5 --
6 -- This file is part of Vicious.
7 --
8 -- Vicious is free software: you can redistribute it and/or modify
9 -- it under the terms of the GNU General Public License as
10 -- published by the Free Software Foundation, either version 2 of the
11 -- License, or (at your option) any later version.
12 --
13 -- Vicious is distributed in the hope that it will be useful,
14 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
15 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 -- GNU General Public License for more details.
17 --
18 -- You should have received a copy of the GNU General Public License
19 -- along with Vicious. If not, see <https://www.gnu.org/licenses/>.
20
21 -- {{{ Grab environment
22 local pcall = pcall
23 local helpers = require("vicious.helpers")
24 local spawn = require("vicious.spawn")
25
26 local success, json = pcall(require, "cjson")
27 if not success then
28 json = require("json")
29 end
30
31 local string = {
32 sub = string.sub,
33 upper = string.upper,
34 }
35 -- }}}
36
37
38 -- Btc: provides current bitcoin price
39 -- vicious.widgets.btc
40 local btc_all = {}
41
42
43 -- {{ Bitcoin widget type
44 function btc_all.async(format, warg, callback)
45 -- Default values
46 if not warg then warg = "usd" end
47
48 local btc = { ["{price}"] = "N/A" }
49 local currency_code = string.upper(warg)
50 local url = "https://api.coindesk.com/v1/bpi/currentprice/" .. currency_code .. ".json"
51 local cmd = "curl "..helpers.shellquote(url)
52
53 -- {{ Checking response
54 local function parse(response)
55 -- If 'response' is not json, 'json.decode' will return Error
56 local status, data = pcall(function() return json.decode(response) end)
57 if not status or not data then
58 return btc
59 end
60
61 btc["{price}"] = string.sub(data["bpi"][currency_code]["rate"], 0, -3)
62 return btc
63 end
64 -- }}
65
66 spawn.easy_async(cmd, function(stdout) callback(parse(stdout)) end)
67 end
68 -- }}}
69
70 return helpers.setasyncall(btc_all)