dispatcher.lua 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. -- Copyright 2008 Steven Barth <steven@midlink.org>
  2. -- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org>
  3. -- Copyright 2017 Matthias Schiffer <mschiffer@universe-factory.net>
  4. -- Licensed to the public under the Apache License 2.0.
  5. local fs = require "nixio.fs"
  6. local json = require "jsonc"
  7. local tpl = require "gluon.web.template"
  8. local util = require "gluon.web.util"
  9. local proto = require "gluon.web.http.protocol"
  10. module("gluon.web.dispatcher", package.seeall)
  11. function build_url(http, path)
  12. return (http:getenv("SCRIPT_NAME") or "") .. "/" .. table.concat(path, "/")
  13. end
  14. function redirect(http, ...)
  15. http:redirect(build_url(http, {...}))
  16. end
  17. function node_visible(node)
  18. return (
  19. node.title and
  20. node.target and
  21. (not node.hidden)
  22. )
  23. end
  24. function node_children(node)
  25. if not node then return {} end
  26. local ret = {}
  27. for k, v in pairs(node.nodes) do
  28. if node_visible(v) then
  29. table.insert(ret, k)
  30. end
  31. end
  32. table.sort(ret,
  33. function(a, b)
  34. return (node.nodes[a].order or 100)
  35. < (node.nodes[b].order or 100)
  36. end
  37. )
  38. return ret
  39. end
  40. function httpdispatch(http)
  41. local request = {}
  42. local pathinfo = proto.urldecode(http:getenv("PATH_INFO") or "", true)
  43. for node in pathinfo:gmatch("[^/]+") do
  44. table.insert(request, node)
  45. end
  46. ok, err = pcall(dispatch, http, request)
  47. if not ok then
  48. http:status(500, "Internal Server Error")
  49. http:prepare_content("text/plain")
  50. http:write(err)
  51. end
  52. end
  53. local function set_language(renderer, accept)
  54. local langs = {}
  55. local weights = {}
  56. local star = 0
  57. local function add(lang, q)
  58. if not weights[lang] then
  59. table.insert(langs, lang)
  60. weights[lang] = q
  61. end
  62. end
  63. for match in accept:gmatch("[^,]+") do
  64. local lang = match:match('^%s*([^%s;-_]+)')
  65. local q = tonumber(match:match(';q=(%S+)%s*$') or 1)
  66. if lang == '*' then
  67. star = q
  68. elseif lang and q > 0 then
  69. add(lang, q)
  70. end
  71. end
  72. add('en', star)
  73. table.sort(langs, function(a, b)
  74. return (weights[a] or 0) > (weights[b] or 0)
  75. end)
  76. for _, lang in ipairs(langs) do
  77. if renderer.setlanguage(lang) then
  78. return
  79. end
  80. end
  81. end
  82. function dispatch(http, request)
  83. local tree = {nodes={}}
  84. local nodes = {[''] = tree}
  85. local function _node(path, create)
  86. local name = table.concat(path, ".")
  87. local c = nodes[name]
  88. if not c and create then
  89. local last = table.remove(path)
  90. local parent = _node(path, true)
  91. c = {nodes={}}
  92. parent.nodes[last] = c
  93. nodes[name] = c
  94. end
  95. return c
  96. end
  97. -- Init template engine
  98. local function attr(key, val)
  99. if not val then
  100. return ''
  101. end
  102. if type(val) == "table" then
  103. val = json.stringify(val)
  104. end
  105. return string.format(' %s="%s"', key, util.pcdata(tostring(val)))
  106. end
  107. local renderer = tpl.renderer(setmetatable({
  108. http = http,
  109. request = request,
  110. node = function(path) return _node({path}) end,
  111. write = function(...) return http:write(...) end,
  112. pcdata = util.pcdata,
  113. urlencode = proto.urlencode,
  114. media = '/static/gluon',
  115. theme = 'gluon',
  116. resource = '/static/resources',
  117. attr = attr,
  118. url = function(path) return build_url(http, path) end,
  119. }, { __index = _G }))
  120. local subdisp = setmetatable({
  121. node = function(...)
  122. return _node({...})
  123. end,
  124. entry = function(path, target, title, order)
  125. local c = _node(path, true)
  126. c.target = target
  127. c.title = title
  128. c.order = order
  129. return c
  130. end,
  131. alias = function(...)
  132. local req = {...}
  133. return function()
  134. http:redirect(build_url(http, req))
  135. end
  136. end,
  137. call = function(func, ...)
  138. local args = {...}
  139. return function()
  140. func(http, renderer, unpack(args))
  141. end
  142. end,
  143. template = function(view)
  144. return function()
  145. renderer.render("layout", {content = view})
  146. end
  147. end,
  148. model = function(name)
  149. return function()
  150. local hidenav = false
  151. local model = require "gluon.web.model"
  152. local maps = model.load(name, renderer)
  153. for _, map in ipairs(maps) do
  154. map:parse(http)
  155. end
  156. for _, map in ipairs(maps) do
  157. map:handle()
  158. hidenav = hidenav or map.hidenav
  159. end
  160. renderer.render("layout", {
  161. content = "model/wrapper",
  162. maps = maps,
  163. hidenav = hidenav,
  164. })
  165. end
  166. end,
  167. _ = function(text)
  168. return text
  169. end,
  170. }, { __index = _G })
  171. local function createtree()
  172. local base = util.libpath() .. "/controller/"
  173. local function load_ctl(path)
  174. local ctl = assert(loadfile(path))
  175. local env = setmetatable({}, { __index = subdisp })
  176. setfenv(ctl, env)
  177. ctl()
  178. end
  179. for path in (fs.glob(base .. "*.lua") or function() end) do
  180. load_ctl(path)
  181. end
  182. for path in (fs.glob(base .. "*/*.lua") or function() end) do
  183. load_ctl(path)
  184. end
  185. end
  186. set_language(renderer, http:getenv("HTTP_ACCEPT_LANGUAGE") or "")
  187. createtree()
  188. local node = _node(request)
  189. if not node or not node.target then
  190. http:status(404, "Not Found")
  191. renderer.render("layout", { content = "error404", message =
  192. "No page is registered at '/" .. table.concat(request, "/") .. "'.\n" ..
  193. "If this URL belongs to an extension, make sure it is properly installed.\n"
  194. })
  195. return
  196. end
  197. http:parse_input(node.filehandler)
  198. local ok, err = pcall(node.target)
  199. if not ok then
  200. http:status(500, "Internal Server Error")
  201. renderer.render("layout", { content = "error500", message =
  202. "Failed to execute dispatcher target for entry '/" .. table.concat(request, "/") .. "'.\n" ..
  203. "The called action terminated with an exception:\n" .. tostring(err or "(unknown)")
  204. })
  205. end
  206. end