luci-base: convert menu nodes to JSON
[oweals/luci.git] / modules / luci-base / luasrc / controller / admin / uci.lua
1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Copyright 2010-2019 Jo-Philipp Wich <jo@mein.io>
3 -- Licensed to the public under the Apache License 2.0.
4
5 module("luci.controller.admin.uci", package.seeall)
6
7 local function ubus_state_to_http(errstr)
8         local map = {
9                 ["Invalid command"]   = 400,
10                 ["Invalid argument"]  = 400,
11                 ["Method not found"]  = 404,
12                 ["Entry not found"]   = 404,
13                 ["No data"]           = 204,
14                 ["Permission denied"] = 403,
15                 ["Timeout"]           = 504,
16                 ["Not supported"]     = 500,
17                 ["Unknown error"]     = 500,
18                 ["Connection failed"] = 503
19         }
20
21         local code = map[errstr] or 200
22         local msg  = errstr      or "OK"
23
24         luci.http.status(code, msg)
25
26         if code ~= 204 then
27                 luci.http.prepare_content("text/plain")
28                 luci.http.write(msg)
29         end
30 end
31
32 function action_apply_rollback()
33         local uci = require "luci.model.uci"
34         local token, errstr = uci:apply(true)
35         if token then
36                 luci.http.prepare_content("application/json")
37                 luci.http.write_json({ token = token })
38         else
39                 ubus_state_to_http(errstr)
40         end
41 end
42
43 function action_apply_unchecked()
44         local uci = require "luci.model.uci"
45         local _, errstr = uci:apply(false)
46         ubus_state_to_http(errstr)
47 end
48
49 function action_confirm()
50         local uci = require "luci.model.uci"
51         local token = luci.http.formvalue("token")
52         local _, errstr = uci:confirm(token)
53         ubus_state_to_http(errstr)
54 end
55
56 function action_revert()
57         local uci = require "luci.model.uci"
58         local changes = uci:changes()
59
60         -- Collect files to be reverted
61         local _, errstr, r, tbl
62         for r, tbl in pairs(changes) do
63                 _, errstr = uci:revert(r)
64                 if errstr then
65                         break
66                 end
67         end
68
69         ubus_state_to_http(errstr or "OK")
70 end