build: split into luci and luci-addons packages
[project/luci.git] / libs / lucid-rpc / luasrc / lucid / rpc / ruci.lua
1 --[[
2 LuCIRPCd
3 (c) 2009 Steven Barth <steven@midlink.org>
4
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9         http://www.apache.org/licenses/LICENSE-2.0
10
11 $Id$
12 ]]--
13 local uci = require "luci.model.uci"
14 local tostring, getmetatable, pairs = tostring, getmetatable, pairs
15 local error, type = error, type
16 local nixio = require "nixio"
17 local srv = require "luci.lucid.rpc.server"
18
19 --- Remote UCI functions.
20 module "luci.lucid.rpc.ruci"
21
22 -- Prepare the remote UCI functions.
23 function _factory()
24         local m = srv.Module("Remote UCI API")
25         
26         for k, v in pairs(_M) do
27                 if type(v) == "function" and v ~= _factory then
28                         m:add(k, srv.Method.extended(v))
29                 end
30         end
31         
32         return m
33 end
34
35 -- Get the associate RUCI instance.
36 local function getinst(session, name)
37         return session.ruci and session.ruci[name]
38 end
39
40 -- Set a new RUCI instance.
41 local function setinst(session, obj)
42         session.ruci = session.ruci or {}
43         local name = tostring(obj):match("0x([a-z0-9]+)")
44         session.ruci[name] = obj
45         return name
46 end
47
48
49 local Cursor = getmetatable(uci.cursor())
50
51 for name, func in pairs(Cursor) do
52         _M[name] = function(session, inst, ...)
53                 inst = getinst(session, inst)
54                 return inst[name](inst, ...)
55         end
56 end
57
58 --- Generate a new RUCI cursor.
59 -- @param session Session object
60 -- @param ... Parameters passed to the UCI constructor
61 -- @return RUCI instance
62 function cursor(session, ...)
63         return setinst(session, uci.cursor(...))
64 end
65
66 --- Generate a new RUCI state cursor.
67 -- @param session Session object
68 -- @param ... Parameters passed to the UCI constructor
69 -- @return RUCI instance
70 function cursor_state(session, ...)
71         return setinst(session, uci.cursor_state(...))
72 end
73
74 --- Custom foreach function.
75 -- @param session Session object
76 -- @param inst RUCI instance
77 -- @param config UCI config
78 -- @param sectiontype UCI sectiontype
79 -- @return section data
80 function foreach(session, inst, config, sectiontype)
81         local inst = getinst(session, inst)
82         local secs = {}
83         inst:foreach(config, sectiontype, function(s) secs[#secs+1] = s end)
84         return secs
85 end